简体   繁体   中英

Why is my quick sort hanging up?

I'm reading in from a file (it's just a small (100 elements) list of random integers) into a vector and trying to use quick sort to sort it, but it hangs up. The quicksort function eventually repeats infinitely i = 0, j = 30, left = 31 and right = 30 at the place where I commented in my code.

#include <iostream>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <fstream>
#include <vector>

using namespace std;

void quicksort(vector<size_t> &fileV, size_t left, size_t right);
void swap(size_t &a, size_t &b);

int main(int argc, char* argv[]){
    if (argc != 2){
        cout << "error: quicks <file name> "<< endl;
        return 1;
    }

    fstream file;
    file.open(argv[1]);
    if (!file.is_open()){
        cout << "error: failed to open file " << argv[1] << endl;
        return 1;
    }

    vector<size_t> fileV;
    size_t ranNum;
    size_t i = 0;
    while(file >> ranNum)
        fileV.push_back(ranNum);

    quicksort(fileV, 0, fileV.size());

    file.close();

    return 0;
}

void quicksort(vector<size_t> &fileV, size_t left, size_t right){
    size_t i = left, j = right, center = (left + right) / 2;
    size_t pivot = fileV[center];

    while (i <= j){
        while (fileV[i] <= pivot)
            i++;
        while (fileV[j] > pivot)
            j--;
        if (i <= j){
            swap (fileV[i], fileV[j]);
            i++;
            j--;
        }
    }

    //repeats infinitely with i = 0, j = 30, left = 31 and right = 30

    if (left < j) 
        quicksort(fileV, left, j);
    if (i < right) 
        quicksort(fileV, i, right);
}

void swap(size_t &a, size_t &b){
    size_t t = a;
    a = b;
    b = t;
}

Your partition algorithm step is wrong. For example, let's say we start with:

[1, 2, 3, 2, 8, 9]
 ^i    ^center  ^j

We go into the while loop, which will first move i up the first element greater than 3 (the 8 ), and j down to the first element less than or equal to 3 (the last 2 ):

[1, 2, 3, 2, 8, 9]
          ^j ^i

At this point, no swap occurs, and we consider our partition done. This is wrong: we needed to have swapped the 2 and the 3 . Regardless of why it ends up infinitely looping somewhere, this implementation has no hope of yielding the correct answer.

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