简体   繁体   中英

quicksort not sorting c++

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;
}

This line looks out of place:

int pivot=numbers.size()/2;

You're picking for your pivot the middle element of the numbers vector regardless of the start and end positions.

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:

    while( i < pivot && i < j)
        i++;
    while( j >= pivot && i < j)
        j--;

should be changed to this:

    while( numbers[i] < pivot && i < j)
        i++;
    while( numbers[j] >= pivot && i < j)
        j--;

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. Eg pivot = numbers[start]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM