@Navin: If I am correctly executing your algorithm on the data in the
original posting, {-1,5,3,-8,4,-6,9}, I get {-1,-6,-8,4,3,5,9}, when the
correct answer is {-1,-8,-6,5,3,4,9}. The array contains the correct
numbers, but the order of the positive numbers and the order of the negtive
numbers is not maintained. You can't swap a number from the front part of
the array with a number from the back part and expect the order of
positives and negatives to remain intact.
Dave
On Saturday, June 30, 2012 12:42:09 AM UTC-5, Navin Gupta wrote:
> @Dave :- a minor change
> Initially, decrement the end pointer till it points to positive number,
> Now end points to the last negative number.
> Now,
> If current is negative , increment current
> If current is positive , swap it with the element at end and decrement
> current and end both
> If current >= end , then break.
> Algo :-
> cur = 0;
> end = size - 1;
> while ( a[end] > 0 && end > 0 ) end - - ;
> while ( cur <end ) {
> if( a[cur] < 0 ) cur++;
> else{
> swap( a[cur], a[end] );
> end - - ;
> } // end of if-else
> } // end of while
> In the above example :- ( 1, -1, 2 ), current points to 1 (cur=0) and end
> points to -1 (end =1 ) after end has been decremented.
> Now swap the element at current and end pointers.
> Now cur = 0, end =0, break condition is reached. the output is :- ( -1, 1,
> 2 )
> Please check.
>
> Navin Kumar Gupta
> Final Year, B.Tech (Hons.)
> Computer Science & Engg.
> National Institute of Technology,Jamshedpur
> Mob - (+91) 8285303045
>
> On Friday, 29 June 2012 22:28:15 UTC+5:30, Dave wrote:
>>
>> @Navin: Try this with {1,-1,2}. current points to the 1 and end points to
>> the 2. Since 1 is positive, the algorithm swaps the 1 and the 2, giving
>> {2,-1,1}. Then it decrements current to point outside the array and end to
>> point to the -1. How can this be right?
>>
>> Dave
>>
>
--
You received this message because you are subscribed to the Google Groups
"Algorithm Geeks" group.
To view this discussion on the web visit
https://groups.google.com/d/msg/algogeeks/-/97r3CtynC8oJ.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/algogeeks?hl=en.