用C ++实现QuickSort的问题

时间:2019-02-11 14:25:47

标签: c++ algorithm quicksort

因此,对于这个简单的代码来说,答案是部分正确的。结果为“ 1 1个 2 3 4 4 2 6 8 5 ”  我认为问题应该与递归和分区有关。我在哪里做错了??

#include <iostream>

using namespace std;


void swap(int* a, int* b){
    int temp = *a;
    *a = *b;
    *b = temp;
}
void quick_sort(int num[], int low, int high){
    int i = low - 1;
    int pivot = num[high];
    for(int j = low; j <= high -1; j++){
        if(num[j] <= pivot){
            i++;
            swap(&num[i], &num[j]);
        }
        else{
            continue;
        }
    swap(&num[i+1], &num[high]);
    quick_sort(num, low, i);
    quick_sort(num, i+2, high);
    }
}

int main(){
    int test[] = {3,1,2,6,5,4,8,1,2,4};
    quick_sort(test, 0, sizeof(test)/sizeof(test[0])-1);
    for(int i = 0; i < sizeof(test)/sizeof(test[0]); ++i){
        cout << test[i] << endl;
    }
    return 0;

}

2 个答案:

答案 0 :(得分:0)

您的问题是for循环。应该在for循环完成后更新i值,然后将i值用于swap和其他quick_sort调用。但是,您的源代码是在for循环内更新的,并用于交换和其他quick_sort调用。这是问题。这是我的解决方案:

#include <iostream>

using namespace std;


void swap(int* a, int* b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}
void quick_sort(int num[], int low, int high) {
    if (low >= high) return;
    int i = low - 1;
    int pivot = num[high];
    for (int j = low; j <= high - 1; j++) {
        if (num[j] <= pivot) {
            i++;
            swap(&num[i], &num[j]);
        }
        else {
            continue;
        }
    } // move to correct line
    swap(&num[i + 1], &num[high]);
    quick_sort(num, low, i);
    quick_sort(num, i + 2, high);
    // } this line should be moved to another line
}

int main() {
    int test[] = { 3,1,2,6,5,4,8,1,2,4 };
    quick_sort(test, 0, sizeof(test) / sizeof(test[0]) - 1);
    for (int i = 0; i < sizeof(test) / sizeof(test[0]); ++i) {
        cout << test[i] << endl;
    }
    return 0;

}

答案 1 :(得分:0)

就像@Loc Tran指出的那样,您的数据透视交换和随后的左右快速排序必须在for循环之外。不需要else continue;。 for循环的目的是为我们的i元素找到position(pivot),以使左侧的所有元素都小于pivot,右侧的所有元素都大于{{ 1}}。

确定位置(pivot)后,通过交换将数据透视图放置在那里,然后在i+1的左侧和右侧进行快速排序。

还应该仅在pivot时进行快速排序。

low < high