c++ - 使用 C++ 实现 QuickSort 的问题

标签 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;

}

最佳答案

您的问题是 for 循环。 i 值应在 for 循环完成后更新,然后使用 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;

}

关于c++ - 使用 C++ 实现 QuickSort 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54632690/

相关文章:

c++ - 在 C++ 编译时输出 typedef 的类型(特别是发生错误时)

javascript - 替换数据 block 中的多个模式

algorithm - 以第一个元素为枢轴的快速排序

algorithm - 随机快速排序最坏情况时间复杂度

C++ - 如何完全包装一个子进程

c++ - '非标准语法;使用 '&'创建一个指向具有线程的成员的指针

javascript - Leetcode 两个数字相加 Q : how to create a linkedlist from a number?

c# - 在 List<T>.Sort() 方法中,项目是否与自身进行了比较?

c++ - UDP NAT打洞示例

algorithm - 寻找满足等式 1/x + 1/y = 1/n 且 x、y 和 n 为整数的不同对 {x, y}