快速排序算法遇到问题
QuickSort algorithm experiencing problems
我不确定我的代码出了什么问题,但在第30行,当递归开始时,我的程序中断,只打印出未排序的数组,而quickSort算法永远不会完成。如果有人知道为什么这个程序不能正常工作,请告诉我。提前谢谢。
#include <iostream>
#include <time.h>
using namespace std;
void quickSort(int qarray[], int l, int r){
int i = l, j = r;
int temp;
int pivot = qarray[(l+r)]/2;
//partitioning
while(i<=j){
while(qarray[i]< pivot)
i++;
while(qarray[j] > pivot)
j--;
if(i<=j){
temp = qarray[i];
qarray[i] = qarray[j];
qarray[j] = temp;
i++;
j--;
}
}
//Recursion of the quicksort algorithm
if(l < j){
quickSort(qarray,l,j);
}
if(i < r){
quickSort(qarray,i,r);
}
}
int main(){
clock_t tStart = clock();
int myArray[26] ={4,2,5,6,1,3,17,14,67,45,32,66,88,
78,69,92,93,21,25,23,71,61,59,60,30,79};
for(int i=0;i < 26;i++){
cout << "Unsorted: " << myArray[i] << endl;
}
quickSort(myArray,0,25);
for(int i=0;i < 26;i++){
cout << "Sorted: " << myArray[i] << endl;
}
double seconds = clock() / double(CLK_TCK);
cout << "This program has been running for " << seconds << " seconds." << endl;
system("pause");
return 0;
}
此行错误(至少):int pivot = qarray[(l+r)]/2;
必须是int pivot = qarray[(l + r) / 2];
将数组的元素除以2是没有意义的。Pivot是索引为(l + r) / 2
的范围的中间元素。
相关文章:
- 编译包含字符串的代码时遇到问题
- 如何在C++向量中奇数元素前面加上值-1,我在使用insert函数时遇到了问题
- 在 for 循环中查找问题时遇到困难
- 代码在我的计算机上运行良好,但是在将其提交给coursera时遇到未知的信号11问题
- 在顶点着色器中使用 OpenGl 的未声明标识符,我在顶点着色器中绘制三角形时遇到问题
- 从其他类访问类时遇到问题
- 打印问题.我在数组中打印值时遇到一些问题
- 使用静态成员声明类时遇到问题
- C++ 填充数组时遇到问题
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- 我在使用C++文件时遇到了一些问题
- 在将字符串放入字符串向量时遇到问题?
- 余数除法和不允许除以零 (c++) 时遇到问题
- 我在C++中使用 getline() 函数时遇到问题
- C++线程安全:如果只有一个线程可以写入非原子变量,但多个线程从中读取. 会遇到问题吗?
- 在我的四叉树实现中遇到问题
- 在 c++ 中循环遍历数组时遇到问题
- 我遇到了黑客排名中的问题"TWO STRINGS"的三个测试用例的分段错误。原因是什么?
- 使用 MinGW 在 Windows 上构建 GLEW 时遇到问题
- 编译 Cilk Plus 程序时遇到问题