INPUT 6, -1, -2, 2, -4, 3, 5
OUTPUT -4, -2,-1 2 ,6 ,3 ,5
This is a very common question asked in which can be of form arranging all even numbers before than odd ones or keeping all 0 values before 1 etc.... And they always expect you to solve in one scan and in place...
METHOD 1
In this we take another array of same size and first push all the negative elements and then in second scan er push all positive elements..
Time Complexity= O(n)
Space COmplexity=O(n)
METHOD 2
We take two pointers ptr1 and ptr2.
ptr1 points to first occurence of positive elements,,
and ptr2 searches the negative number to the right of ptr1 if we do not find any -ve number we break...
else we we swap them and find our new ptr1 which is obviously greater than the previous value
No comments:
Post a Comment