Hi,
How can i modify the quicksort algorithm so that it sorts in descending order?
thxn
This is a discussion on Make quicksort work the other way? within the C Programming forums, part of the General Programming Boards category; Hi, How can i modify the quicksort algorithm so that it sorts in descending order? thxn...
Hi,
How can i modify the quicksort algorithm so that it sorts in descending order?
thxn
Sure, just change the comparison function to return negative values of what it normally returns...
qsort (base, n, sizeof(int), cmp);Code:int cmp(int a, int b) { return (a - b); } int othercmp (int a, int b) { return (b - a); }
sorts the array in ascending order....
qsort(base, n, sizeof(int), othercmp);
sorts the array in descending order.
Callou collei we'll code the way
Of prime numbers and pings!
See where it says "control order of alphebetizing?
Code:#include<stdio.h> #include<stdlib.h> #include<string.h> int IsLess(char * x, char * mid) { //control the order of alphebetizing here with < or > if(strcmp( x,mid) < 0) return -1; else return 1; } char * GetRecord(char * a[], int x) { char * temp = (char*) malloc (sizeof(char) * 20); temp = a[x]; return temp; } void QSort(char * a[], int left, int right) { int i = left; int j = right; char * temp = NULL; //frees placeholder during recursive call free(temp); //get middle record temp = GetRecord(a, (i+j) / 2); do { while (IsLess(GetRecord(a,i), temp) < 0 && i < right) i++; while (IsLess(temp,GetRecord(a,j)) < 0 && j > left) j--; //swap if( i <= j) { temp = a[i]; a[i] = a[j]; a[j] = temp; i++; j--; } }while( i <= j); //recursive calls if(left < j) QSort(a,left,j); if(i < right) QSort(a,i,right); } int main() { int i; const int size = 5; //jagged array rather than a smooth array[x][size] char * array[size] = {"namev","namee","namex","namea","namen" }; QSort(array, 0, size - 1); printf("Sorted array of strings.\n"); for(i = 0; i < size; i++) { printf("%s\n",array[i]); } return 0; }
mmmm i think it really depends on the version of quicksort algorithm you have right? COz mine has only three parameters.
Ok then, nevermind,i 'll sort out myself.
> mmmm i think it really depends on the version of quicksort algorithm you have right
There is only one, it's called qsort and it's found in stdlib.h
And you use it as QuestionC posted
Any other qsort is some non-standard implementation which you would need to provide more details on (if you're still stuck)