I've done the code below to try and implement Quicksort and it works... almost. It switches the positions of the last two items to be sorted.
Example: (using some randomly generated numbers)
- it seems to do this no matter how many elements are generated and sorted
20565
19169
17456
15724
11478
3465
0
41
a is an array that's given, p is a pivot, and r is the size.
Code:void Quick_Sort (int* a, int p, int r) { int q; if(p < r){ q = Partition(a, p, r); Quick_Sort(a, p, q-1); Quick_Sort(a, q+1, r); } } // Quick_Sort int Partition(int* a, int p, int r) { int x = a[r]; int i = p-1; int temp; for(int j=p; j <= r-1; j++){ if(a[j] <= x){ i = i+1; temp = a[i]; a[i] = a[j]; a[j] = temp; } // end if } // end for temp = a[i+1]; a[i+1] = a[r]; a[r] = temp; return i+1; } // Partition




Reply With Quote