c++ - 计算快速排序 C++ 中的比较和移动次数

标签 c++ arrays quicksort

我的任务是开发一个程序,该程序以数组中的第一个元素作为枢轴值来实现快速排序算法。我已经设法通过在数组中使用 20 个元素来进行排序。

现在,我想计算排序过程中比较和移动的次数。我已经尝试过此代码,但输出似乎不正确。比较和 Action 不断打印出来。我怎样才能只打印一次 Action 和比较?希望有人愿意帮助我。提前致谢。

比较和移动代码:

int partition1(int arr[], int start, int end) { //select first element as pivot value
int pivot = arr[start];
int L = start + 1;
int R = end;
int temp = 0;
int compr = 0;
int move = 0;

while (true) {
    while ((L < R) && (arr[R] >= pivot)) {  //bringing R to the left
        --R;
        compr++;
    } 
    while ((L < R) && (arr[L] < pivot)) {   //bringing R to the right
        ++L;
        compr++;
    }
    if (L == R) {   //If they coincide
        break;
    } 
    //swapping L and R
    temp = arr[L];
    arr[L] = arr[R];
    arr[R] = temp;
    move += 2;
}

cout << "Comparison : " << compr << endl;
cout << "Moves : " << move << endl;

if (pivot <= arr[L]) {  //special case
    return start;
} 
else {
    arr[start] = arr[L];  //real pivot
    arr[L] = pivot;
    return L;
} }

这个是快速排序函数:

void quickSort(int arr[], int start, int end) {
int boundary;
if (start < end) {
    boundary = partition1(arr, start, end);
    quickSort(arr, start, boundary - 1);
    quickSort(arr, boundary + 1, end);
} }

最佳答案

在你的while ((L < R) && (arr[R] >= pivot))如果条件为false,则循环再进行一次比较,这就是为什么你应该增加 compr 两个循环之前:

int partition1(int arr[], int start, int end, int & compr, int & move) { //select first element as pivot value
int pivot = arr[start];
int L = start + 1;
int R = end;
int temp = 0;
//int compr = 0;
//int move = 0;
while (true) {
compr++; // !!!
while ((L < R) && (arr[R] >= pivot)) {  //bringing R to the left
    --R;
    compr++;
} 
compr++; // !!!
while ((L < R) && (arr[L] < pivot)) {   //bringing R to the right
    ++L;
    compr++;
}
... // the same lines to the end of function partition1, except of printing compr and move
}

void quickSort(int arr[], int start, int end, int & compr, int & move) {
int boundary;
if (start < end) {
    boundary = partition1(arr, start, end, compr, move);
    quickSort(arr, start, boundary - 1, compr, move);
    quickSort(arr, boundary + 1, end, compr, move);
} }

int main() {
    int compr = 0;
    int move = 0;
    quickSort( { 3, 2, 4, 1 }, 0, 3, compr, move );

    cout << "Total comparison : " << compr << endl;
    cout << "Total moves : " << move << endl;
}

关于c++ - 计算快速排序 C++ 中的比较和移动次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41318970/

相关文章:

c++ - 打开一个文件程序 w/while 循环 C++

c++ - 如何填充包含指针数组的结构体数组

c++ - SOCKET 没有命名类型

java - 如何将多个字节加在一起?

javascript - 通过在 javascript 中使用 RegExp 包含标签来过滤用户列表数组

ios - Swift 上的数组比较未按预期工作

java - 快速排序。线程中出现异常 "main"java.lang.StackOverflowError

algorithm - 快速排序时间复杂度最佳案例输入

c++ - 如果嵌套 extern "C"会发生什么?

java - 实现快速排序似乎比归并排序花费更多时间