Trying to write a quick sort and have spent awhile debugging. The problem seems to be in the second recursive call, but I can't figure out where I'm off. Any pointer would be awesome. Thanks.
void quickSort(vector<int> &list, int left, int right){
int pivot = left;
int temp = right;
if(left >= right - 1)
return;
while (left != right) {
if (pivot == left){
if (list[pivot] > list[right]) {
//-------------------------
int tempList = list[right];
list[right] = list[pivot]; // Swap for now
list[pivot] = tempList;
//-------------------------
pivot = right;
left++;
}else{
right--;
}
}else{
if (list[pivot] < list[left]) {
//-------------------------
int tempList = list[left];
list[left] = list[pivot]; // Swap for now
list[pivot] = tempList;
//-------------------------
pivot = left;
right--;
}else{
left++;
}
}
}
quickSort(list, 0, right-1);
quickSort(list, right + 1, temp);
}
This is how I'm making the data set right now:
srand(time(0));
vector<int> list;
vector<int> sortedList;
int i;
for (i=0;i<10;i++) list.push_back(rand() %100);
I got a data set of 38 65 26 22 86 64 13 28 57 18
and got an output of 13 18 22 26 28 38 57 64 86 65
It's usually an element in the last half, but it's also not every time. Maybe 1 in 4 times.