I am trying to write a quicksort function to sort anywhere between 10 and 1,000,000 numbers. It iterates through everything but does not sort, just prints the vector as is.
For some reason it jumps out of the while loop way too soon.
The test input I’m using is: (3 6 2 5 1 7 9 10 4 8).
And it’s output: (1 2 6 5 3 7 9 10 4 8)
int main()
{
std::cout << "Which file would you like to sort?\n";
std::cin >> file;
std::ifstream in(file.c_str());
// Read all the ints from in:
std::copy(std::istream_iterator<int>(in), std::istream_iterator<int>(),
std::back_inserter(numbers));
int max = numbers.size();
quickSort(numbers, 0, max-1);
// Print the vector with tab separators:
std::copy(numbers.begin(), numbers.end(),
std::ostream_iterator<int>(std::cout, "\t"));
std::cout << std::endl;
return 0;
}
void quickSort(vector<int> &numbers, int start, int end)
{
int i = start;
int j = end;
int pivot=numbers[start];
int temp;
while( i != j )
{
while( numbers[i] < pivot && i < j)
i++;
while( numbers[j] >= pivot && i < j)
j--;
temp = numbers[i];
numbers[i] = numbers[j];
numbers[j] = temp;
if( j < start )
{
quickSort( numbers, start, j );
}
if( i < start )
{
quickSort( numbers, i, end);
}
}
return;
}
Possibly among other things, you aren’t actually looking at the contents of the vector when you move your indices to find a swap. This section:
should be changed to this:
As one of the commenters mentioned, the bigger lesson is to learn to use a good debugger to step through your code.
Similarly, you should be selecting pivot as an array value. E.g.
pivot = numbers[start]