I am debugging my code for a quick sort algorithm in C. It compiles but fails with a “Segmentation fault” when running it.
Can anybody help me to debug it and give me the working version of my code? I know there are existing and working ones on the internet. But what I really want is to find the bug of my own code.
void myQuickSort(int list[],int head, int tail)
{
int m = head;
int n = tail;
int key = list[m];
++head;
while(head < tail)
{
while(list[head] < key)
{
++head;
}
while(list[tail] >= key)
{
--tail;
}
//swamp two elements, to divide the array to two groups
int temp = list[head];
list[head] = list[tail];
list[tail] = temp;
}
//get the pivot element in dividing position
int temp = list[m];
list[m] = list[head];
list[head] = temp;
myQuickSort(list, m, head-1);
myQuickSort(list, head+1, n);
}
Your function will never exit.
It will keep calling itself until the call stack is full and cause a stack overflow exception.
The compiler should generate a warning for this:
You need an exit condition, something along the lines of:
Also, make sure you call the function like:
the final parameter must be 1 less than the length of the array since C++ arrays are 0-based.
You also need one extra check in your while loops:
or else you might pass the end of the array.