Monday 2 May 2011

Partition an array into positive and negative values

 

Question

You are given the below array

{-3,4,3,-2,-8,6,13,-15}

Now find the point where the negative numbers shifts into positive space. The performance should be at most O(n) and there should be no extra space usage.

Example Output: –3, –2, –8, –15, 4,3,6,13

The index returned should be 4 in this case.. (array index starts from 0)

Concept

    Just think a small concept about how to solve this. If you can get this worked out in mind, you have not forgotten the Partition algorithm we studied for quick sort. (http://analgorithmaday.blogspot.com/2011/02/partitioning-algorithmin-place.html)

In partition algorithm for quick sort, we just move shorter elements to the initial index and larger elements into the end indices. We have to follow the similar fashion here to partition this array. But out pivot is already known and obvious..

Our pivot for this array is always 0.. :) and we have to traverse the whole array once to check for negative numbers (<0). If you find a number less than zero, just put that into our i list. There will be no swapping if the negative numbers are found in-order.

The performance of this code will be O(n) worst case and there is no extra space.

Code

int partition_sign(int* arr, int start, int end)
{
    int i,j, pivot;
    pivot = 0;
    i=start-1;
    for(j=start; j<=end; j++)
    {
        if(arr[j] <= pivot) {
            i=i+1;
            if(i!=j)
                swap(arr[i], arr[j]);
        }
    }
    return i+1;
}
 
 
void main()
{
    int A[] = {-3,4,3,-2,-8,6,13,-15};
    int pos = partition_sign(A, 0, 7);
}
  • The above partition logic is same as Quick sort partition.. It has many practical use like this. :)
  • Instead of >=, we use <= so that all negative numbers come in left side (in-order of occurrence) and positive numbers to the right side (in wrong order of occurrence)
  • If you use >=, you will get negative numbers in right side (in wrong order).
  • The main use of such logic is to eliminate negative numbers from the array!!

3 comments:

Anirvana said...

Doesn't work for this input: 4 -8 6 -3 5 -9 3
Gives -8 -3 -9 4 5 6 3 instead of -8 -3 -9 4 6 5 3

vprajan said...

it places negative numbers in-order.. but not the positive ones.. if you want the positive as well in-order, then we need place even the positives in order.. we need to further partition the positive ones to get the order.. or select the least positive as pivot..

Anonymous said...

#include

int main()
{
int i,j,temp,n;


int a[13] ={-1,9,0,1,2,4,-5,6,-8,-8,-7,9,10};
i=0;
j=12;
while(i=0)
{
if(a[j]<0)
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
j--;
}
else
{
j--;
continue;
}
}
i++;

}

for(i=0;i<12;i++)
printf("%d ",a[i]);
return 0;


}


//this code is working fine..

Post a Comment