Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting Array in O(n) complexity

I was asked an interesting question at my interview at Atrenta. It was to sort an array with an complexity of O(n) which I said is not possible but he insisted it is, even after the interview.

It is like this.

You have an array, lets say : [1,0,1,0,1,1,0] and this needs to be sorted. What ever has to be done within the array (in the sense no other data structure involved.

I haven't and I don't think it is possible to do any sort with an complexity of O(n). The best I could think of is O(n * log n) and my knowledge comes from Wikipedia.

Please give me your ideas and well a way to do it if you know.

like image 345
Ziyan Junaideen Avatar asked Dec 09 '25 13:12

Ziyan Junaideen


2 Answers

In your example there are only two different values in the array, so you could use counting sort:

zero_count = 0
for value in array:
    if value == 0:
        zero_count += 1
for i in 0 ... zero_count:
    array[i] = 0
for i in zero_count ... array.size:
    array[i] = 1

Radix sorts are a family of more generally applicable O(n) sorts.

It is comparison sorts that require Omega(n * log n) comparisons on average and hence cannot run in worst-case or average-case linear time.

like image 73
Steve Jessop Avatar answered Dec 12 '25 07:12

Steve Jessop


Traverse the array from both ends and Swap 1's and 0's when needed.Runs in O(n) but has all the if conditions(bruteforce like approach.probably not the expected answer) ;)

int i = 0 ;
int j = array.size -1 ;
for ( i = 0 ; i < j ; ) {

    if( array[i] == 1) {
        if( array[j] == 0 ) {
            array[j] = 1 ; array[i] = 0 ; //Swap 
            i++; j--; 
            continue;
        }
        //else
            j--;
            continue;

    }
   //else
        if( array[j] == 0 ) {
            i++; 
            continue;
        }

        //else 
            i++ ;
            j--;            
}
like image 34
Dinushan Avatar answered Dec 12 '25 08:12

Dinushan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!