QuickSort 中的分段
Segmentation in QuickSort
当我尝试 运行 这个 QuickSort 时,我得到了一个分段 fault:11,但它编译得很好。我 运行 将其与驱动程序连接,这就是我使用 quicksort() 和 quicksortR() 的原因。是什么导致了分段?
/* -------- Quick sort stuff starts here --------- */
int partition(int array[], int start, int stop) {
int compars = 0;
int pivot = array[stop];
int i = start - 1;
for (int j = start; j <= stop - 1; j++) {
if (array[j] <= pivot) {
i++;
int temp = array[j];//swaps values of i and j
array[j] = array[i];
array[i] = temp;
}
compars++;
}
int temp = array[i + 1];
array[i + 1] = array[stop];
array[stop] = temp;
return compars;
}
int quickSortR(int array[], int start, int stop) {
int compars = 0;
int mid = array[stop];
if (start < stop) {
compars = compars + partition(array, start, stop);
quickSortR(array, start, mid - 1);
quickSortR(array, mid+1, stop);
}
return compars;
}
int quickSort(int array[], int n) {
return quickSortR(array, 0, n);
}
/* ----------- end quick sort stuff ----------------- */
I'm getting a segmentation fault:11 when I try to run this QuickSort, but it compiles fine
请注意:程序编译意味着编译器理解您希望程序做什么。编译器决不会检查您的程序所做的事情是否有意义。
如果它知道你想做什么,它为什么不自己编写程序呢?
您调用 quicksort
时将数组元素的数量作为 stop
参数,但您将主元初始化为 int pivot = array[stop];
。您正在阅读数组末尾。未定义的行为。
代码中可能还有其他问题,但这本身就可以解释崩溃。
当我尝试 运行 这个 QuickSort 时,我得到了一个分段 fault:11,但它编译得很好。我 运行 将其与驱动程序连接,这就是我使用 quicksort() 和 quicksortR() 的原因。是什么导致了分段?
/* -------- Quick sort stuff starts here --------- */
int partition(int array[], int start, int stop) {
int compars = 0;
int pivot = array[stop];
int i = start - 1;
for (int j = start; j <= stop - 1; j++) {
if (array[j] <= pivot) {
i++;
int temp = array[j];//swaps values of i and j
array[j] = array[i];
array[i] = temp;
}
compars++;
}
int temp = array[i + 1];
array[i + 1] = array[stop];
array[stop] = temp;
return compars;
}
int quickSortR(int array[], int start, int stop) {
int compars = 0;
int mid = array[stop];
if (start < stop) {
compars = compars + partition(array, start, stop);
quickSortR(array, start, mid - 1);
quickSortR(array, mid+1, stop);
}
return compars;
}
int quickSort(int array[], int n) {
return quickSortR(array, 0, n);
}
/* ----------- end quick sort stuff ----------------- */
I'm getting a segmentation fault:11 when I try to run this QuickSort, but it compiles fine
请注意:程序编译意味着编译器理解您希望程序做什么。编译器决不会检查您的程序所做的事情是否有意义。 如果它知道你想做什么,它为什么不自己编写程序呢?
您调用 quicksort
时将数组元素的数量作为 stop
参数,但您将主元初始化为 int pivot = array[stop];
。您正在阅读数组末尾。未定义的行为。
代码中可能还有其他问题,但这本身就可以解释崩溃。