Showing posts with label algorithm. Show all posts
Showing posts with label algorithm. Show all posts

Saturday, December 7, 2013

Sum of two's complement of n integers

I saw a sum of two's complement puzzle on some site and started doing it I was able to do solve the problem but couldn't able to finish below 5 sec, then i came up with the above generating function helps me to solve in less time.  Below is a sample code in Java


public static class SumOfTwosComplement{
        int bitPositionCount=2;
        long bitPositionDiff=1;
        int diffIncrement=1;
        long occurence=1;
        int positionCount;
      
        public long calculate(int i){
            if(i==0){
                positionCount=0;
                return 0;
            }else if(i==1){
                positionCount=1;
                return 1;
            }
              
          
            for(;bitPositionCount<=i && bitPositionCount >=0;){
                occurence+=bitPositionDiff;
                bitPositionDiff=2*bitPositionDiff+diffIncrement;
              
                diffIncrement=2*diffIncrement;
              
                positionCount=bitPositionCount;
                bitPositionCount=bitPositionCount*2;
              
            }
            return occurence;
        }
    }


Monday, July 27, 2009

Batchers Bitonic sort

The example i am showing will only works for 2^n numbers.

First,we need to break up the given sequence into smaller parts,we call them individual sorting parts( initially two numbers in a part, for every step it will doubles). Now sort first part in increasing and the second in decreasing order and continue like this to the end.

Second, after sorting, if the sorted part having more than two number, then you need to sort numbers with-in, and ascending or descending order depends on which part it is.

example for 8 numbers:



example for 4 numbers: