English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

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 < n; x++)
... {
... for(int y = 0; y < n - 1; y++)
... {
... if(*array[y] > *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

2006-12-10 12:29:58 · 3 answers · asked by duffusd 3 in Computers & Internet Programming & Design

3 answers

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]

2006-12-10 14:28:45 · answer #1 · answered by Mark W 1 · 1 0

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>=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.

2006-12-10 12:40:46 · answer #2 · answered by srinivasan7386 2 · 0 1

All you have to do is reverse the > sign in the comparison to make it a < sign, then the sort will be in reverse order.

2006-12-10 13:32:52 · answer #3 · answered by Steve A 2 · 1 0

fedest.com, questions and answers