【问题标题】:Calculate number of comparison and moves in quicksort C++计算快速排序 C++ 中的比较次数和移动次数
【发布时间】:2016-12-25 05:48:00
【问题描述】:

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

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

比较和动作的代码:

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

【问题讨论】:

    标签: c++ arrays quicksort


    【解决方案1】:

    在您的while ((L &lt; R) &amp;&amp; (arr[R] &gt;= 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;
    }
    

    【讨论】:

      【解决方案2】:

      最简单的方法是将comprmove 定义为全局 变量(仅用于调试目的),然后在运行结束时打印值。

      【讨论】:

      • 谢谢您的建议。我只想问,我计算移动和比较的代码是否正确?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多