Consider the following algorithm:
void qsort(int arr[], int left, int right) {
if (left < right) {
int index = partition(arr, left, right);
qsort(arr, left, index - 1);
qsort(arr, index + 1, right);
}
}
int partition(int arr[], int left, int right) {
int pivot = arr[right];
int i = left - 1;
for (int j = left; j < right; j++) {
if (arr[j] <= pivot) {
++i;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[right]);
return i + 1;
}
inline void swap(int* i, int* j) {
int temp = *i;
*i = *j;
*j = temp;
}
After I fixed the segfaults, I noticed that the algorithm always produces a garbage value at arr[0]
. So if the input array is: 5 5 1 3 7 0 0 0 3
, the output is -858993460 0 0 0 1 3 3 5 5
. I've ran this through a debugger numerous times and nevertheless I still have no idea where the garbage value comes from. What's more interesting is that in Java pretty much the same algorithm works perfectly.
edit
The initial function is called like this: qsort(arr, 0, 9);
where 9 is the length of the array - 1.