Here's an instrumented version of your code. Since you didn't provide a swap()
function, I wrote that; I also wrote dump_data()
to print the contents of a segment of an array, and a main()
for testing. On the basis of the limited testing I've done, the sort works. Given that you say it doesn't, I suspect that your swap()
code may be faulty; either that or your test harness code is faulty (or my test just happens to be the case that works!).
#include <stdio.h>
static inline void swap(int *a, int *b) { int c = *a; *a = *b; *b = c; }
static void dump_data(const char *tag, int *data, int first, int last)
{
printf("%s: (%d:%d)\n", tag, first, last);
for (int i = first; i <= last; i++)
printf(" %d", data[i]);
putchar('\n');
}
static
int partition(int arr[], int first, int last)
{
int pivot = arr[first];
int low = first;
int i = first + 1;
while (i <= last)
{
if (arr[i] < pivot)
{
low++;
swap(&arr[i], &arr[low]);
}
i++;
}
swap(&arr[first], &arr[low]);
return low;
}
static
void quick_sort(int arr[], int first, int last)
{
if (first < last)
{
dump_data("-->> QS", arr, first, last);
int pivot_pos = partition(arr, first, last);
printf("Pivot: arr[%d] = %d\n", pivot_pos, arr[pivot_pos]);
quick_sort(arr, first, pivot_pos - 1);
dump_data("-1-- QS", arr, first, pivot_pos - 1);
quick_sort(arr, pivot_pos + 1, last);
dump_data("-2-- QS", arr, pivot_pos + 1, last);
dump_data("<<-- QS", arr, first, last);
}
}
int main(void)
{
int data[] = { 9, 2, 4, 7, 1, 3, 8, 6, 5 };
int size = sizeof(data) / sizeof(data[0]);
dump_data("Before", data, 0, size - 1);
quick_sort(data, 0, size - 1);
dump_data("After", data, 0, size - 1);
return 0;
}
Example run:
Before: (0:8)
9 2 4 7 1 3 8 6 5
-->> QS: (0:8)
9 2 4 7 1 3 8 6 5
Pivot: arr[8] = 9
-->> QS: (0:7)
5 2 4 7 1 3 8 6
Pivot: arr[4] = 5
-->> QS: (0:3)
3 2 4 1
Pivot: arr[2] = 3
-->> QS: (0:1)
1 2
Pivot: arr[0] = 1
-1-- QS: (0:-1)
-2-- QS: (1:1)
2
<<-- QS: (0:1)
1 2
-1-- QS: (0:1)
1 2
-2-- QS: (3:3)
4
<<-- QS: (0:3)
1 2 3 4
-1-- QS: (0:3)
1 2 3 4
-->> QS: (5:7)
7 8 6
Pivot: arr[6] = 7
-1-- QS: (5:5)
6
-2-- QS: (7:7)
8
<<-- QS: (5:7)
6 7 8
-2-- QS: (5:7)
6 7 8
<<-- QS: (0:7)
1 2 3 4 5 6 7 8
-1-- QS: (0:7)
1 2 3 4 5 6 7 8
-2-- QS: (9:8)
<<-- QS: (0:8)
1 2 3 4 5 6 7 8 9
After: (0:8)
1 2 3 4 5 6 7 8 9
More thorough testing would automatically verify that the result is in fact sorted, and also have a larger array with dummy elements that the post-sort checking ensures has not been changed, and would have multiple test runs of different sizes (including 0, 1, 2, 3, 4, and then some larger sizes). This simply tests correctness. To test performance, you do things like test already sorted data, or all values the same, or reverse sorted data, or organ-pipe formations (both ∧ and ∨ form), etc, with and without repeats in the data (as well as random sequences).