【发布时间】:2020-04-27 16:53:19
【问题描述】:
我的快速排序算法有问题。当“cout”语句未注释或调试时,它似乎可以正确运行,但除此之外,它通常(但不总是)给我一个“线程 1:EXC_BAD_ACCESS(代码=2,地址=0x7ffeef3ffff8)”错误。有谁知道如何解决这一问题?起初我以为是随机数生成器,但即使在我对分区枢轴进行去随机化后,它仍然继续发生。
代码的主要部分是名为“Partition”和“Q_Sort”的两个函数。 “Switch”只是交换分区内的元素位置,“Rand”生成一个随机整数,“Disp”只是显示向量。 谢谢。
#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <array>
#include <time.h>
#include <cstdlib>
using namespace std;
//Display vector
void Disp(vector<double> vect){
if (vect.size() == 1){
cout << "{" << vect[0] << "}" <<endl;
}
else if(vect.size() < 1){
cout << "{" << "}" <<endl;
}
else{
for (int ii = 0; ii < vect.size(); ii++) {
if (ii == 0) {
cout << "{" << vect[ii] << ", " << flush;
continue;
}
if (ii == vect.size() - 1) {
cout << vect[ii] << "}" << endl;
continue;
}
cout << vect[ii] << ", " << flush;
}
}
}
//Random integer
int Rand(int range){
srand((unsigned) time(0));
int r = rand() % range;
return r;
}
//Switch
void Switch(vector<double> &vect,int switcher ,int switchee){
if(switchee != switcher){
int old = vect[switchee];
vect[switchee] = vect[switcher];
vect[switcher] = old;
}
}
//Partition
tuple<int,int,int,int> partition(vector<double> &vect, int around, int start, int end){
// cout<<"Around: " <<around<<endl;
double num = vect[around];
Switch(vect,around,start);
int i = start;
int j = start + 1;
int m = start;
int mj = start;
while(j < end){
// cout<<endl;
if(vect[j] >= num){
if(vect[j] == num){
Switch(vect, mj + 1, j);
mj +=1;
}
j += 1;
continue;
}
else if(vect[j] < num){
Switch(vect,mj + 1, j);
Switch(vect,m,mj + 1);
mj += 1;
m += 1;
j += 1;
}
}
// cout<<"End update : "<<endl;
return {m,mj,j - 1,i};
}
void Q_sort(vector<double> &vect,int around, int start, int end){
auto [mm, mmjj, jj, ii] = partition(vect,around, start, end);
// cout<<"Left "<<endl;
// LEFT
int startL = ii; // startL = 0;
int endL = mm ;
// cout<<endl<< "New vector "<<endl;
// Disp(vect);
// cout<<"end "<< endL<<endl;
// cout<<"start "<< startL<<endl;
if(endL - startL > 0){
int r = Rand(endL - startL) + startL;
Q_sort(vect, r,startL,endL);
}
//RIGHT
int startR = mmjj; //+ 1;
int endR = jj;
// cout<<"Right "<<endl;
// cout<<endl<< "New vector "<<endl;
// Disp(vect);
// cout<<"end "<< endR<<endl;
// cout<<"start "<< startR<<endl;
//
if (endR - startR> 1){
int r = Rand(endR - startR) + startR;
Q_sort(vect,r,startR,endR + 1);
}
}
int main(int argc, const char * argv[]) {
vector<double> x{1,5,3,5,4,7,2,14,7,14,4};
Q_sort(x, 0, 0, x.size());
Disp(x);
std::cout << "Hello, World!\n";
return 0;
}
【问题讨论】:
-
你用的是什么调试器?