我正在进行这项任务,以开发一个程序来实现快速排序算法,并将数组中的第一个元素作为透视值。我已经设法通过在数组中使用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);
} }
答案 0 :(得分:1)
在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;
}
答案 1 :(得分:0)
最简单的方法是将compr
和move
定义为全局变量(仅用于调试目的),然后在运行结束时打印值。