【发布时间】:2021-09-17 02:46:49
【问题描述】:
代码:
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
void partition(int *A, int start, int end){ //end is the position of the last number
cout<<"start is "<<start<<" end is "<<end<<endl;
if(end - start+1 > 1){
int i = start + 1, j = start + 1, pivot = A[start];
while(j <= end){
if(A[j] <= pivot){
swap(A[j], A[i]);
i++;
}
j++;
}
swap(A[start], A[i-1]);
partition(A, start, i-1);
partition(A, i, end);
}
}
void QuickSort(int *A, int n){
partition(A, 0, n-1);
}
int main() {
int n, method;
string sortMethod[ ] = {
"Insertion sort", "Selection sort", "Bubble sort", "Merge sort", "Quick sort"
};
int m = sizeof(sortMethod)/sizeof(string);
srand(time(0));
while (true){
cout << "Number of test marks: ";
cin >> n;
if ( n==0 ) break;
int *A = new int[n];
for (int i=0; i < n; i++) cin>>A[i];
//A[i] = rand()%101;
for (int i=0; i < n; i++)cout << A[i] << " ";
cout<<endl<<endl;
cout << "Sorting method: \n";
for (int i=0; i < m; i++) cout << i+1 << ": " << sortMethod[i] << endl;
// cin >> method;
method = 5;
cout<<endl;
int t = time(0);
QuickSort(A,n);
if (method > m) continue;
cout << sortMethod[method-1] << endl;
if (n <= 100) {
for (int i=0; i < n; i++) {
if (i> 0 && i%10==0) cout << endl;
cout << A[i] << " ";
}
cout << endl;
}
else {
cout << "Sorting completed in " << time(0) - t << " sec.\n";
}
cout << endl;
}
cout << "Program ends here."<<endl;
return 0;
}
当我的某些输入数字具有相同的值时,我会收到“分段错误:11”。
例如,“4 7 7 3 1”的输入将产生以下输出的无限行:“start is 1 end is 3”。
请问我应该如何改进我的代码?我知道当您尝试访问无效内存时会发生 Segfault 11,我认为这很可能是我在这里所做的,尽管我似乎无法识别错误。谢谢!
【问题讨论】:
-
请不要标记未使用的语言。
-
您是否尝试过通过调试器逐步运行您的代码?我的经验是,在这种情况下,人们经常会找到这些错误的原因。
-
-fsanitize=addr非常擅长找出此类问题的原因 -
为了测试和调试崩溃之类的东西,请学习minimal reproducible example的概念。删除除最低限度之外的所有代码以复制崩溃,并使用硬编码值而不是用户输入。
-
在这种情况下另一个有用的工具是内存调试器,例如 valgrind。
标签: c++ algorithm sorting quicksort