Saturday, May 22, 2010

C++ bubble sort?

Alright, i've been using bubble sort, i found some code on Cprogramming.com, but i can't figure out how to modify it to work in descending order.


Its sorting a Pointer array. (int** array = new int*[n])


IntPtr is declared as int*.


n is the size of the array...


Yahoo was being stupid and taking away my new lines, so, if it does it again, the '...' means its a new line, this is just incase


:::CODE BEGIN:::


...void sortDown(IntPtr* array, int n)


... {


... for(int x = 0; x %26lt; n; x++)


... {


... for(int y = 0; y %26lt; n - 1; y++)


... {


... if(*array[y] %26gt; *array[y+1])


... {


... IntPtr temp = array[y+1];


... array[y+1] = array[y];


... array[y] = temp;


... }


... }


... }


...}


Now i need to create a function called sortUp, same parameters as the first one, still void, but it needs to sort it in descending order

C++ bubble sort?
The order of ANY sort is determined by the comparison operation. Here, you are determining that 2 elements are out of order if the one that appears first (here array[y]) is greater than the one that appears after it (array[y+1]) and if it is, you swap. That means you are saying that having a first element greater than the second element is "wrong", which means you want lower valued elements first (descending order). The short answer is reverse your comparison (if array[y]%26lt;array[y+1).
Reply:All you have to do is reverse the %26gt; sign in the comparison to make it a %26lt; sign, then the sort will be in reverse order.
Reply:You know the usual bubble sort method. Now all you have to do is to print the array elements in reverse order like as follows


for(i=n;i%26gt;=0;i--)


{


printf(.....);//the usual stuff


}


If you don't like this, then I have another idea for you.


Create a temporary array which has the same size as this one.


Say your array name is b[].All you have to do is store the array elements in reverse order like this.


Try to use a while loop here.


{i=0;


j=n;


while(i!=n)


{


b[j]=a[i];


j--;


i--;


}


now you will be able to see the elements stored in reverse order.


Do this after the sortDown method. That way you will have all the elements sorted in descending order.


Hope this helps you. All the best.


No comments:

Post a Comment