我正在编写一个整数的快速排序算法,我在srand函数中得到一个奇怪的段错误。这是sort.h的代码:
int distributePivot (int *a, int left, int pivot, int right) {
int i, j;
if (pivot != right)
swapInt(&pivot, &right);
i = left;
j = right - 1;
while (i < j) {
while (i < j && a[i] <= a[right])
i++;
while (j > i && a[j] >= a[right])
j--;
if (i < j)
swapInt(&a[i], &a[j]);
}
if (i < right)
swapInt(&a[i], &a[right]);
return i;
}
void intArrayQuickSort (int *a, int left, int right) {
int pivot;
if (left < right) {
pivot = rand() % (right - left +1) + left;
pivot = distributePivot(a, left, pivot, right);
intArrayQuickSort (a, left, pivot -1);
intArrayQuickSort (a, pivot, right);
}
}
这是sort-test.c的调用:
srand(time(NULL));
intArrayQuickSort(temp, 0, n - 1);
其中temp
是指向整数的指针。
这是我在gdb中执行它时遇到的错误:
Program received signal SIGSEGV, Segmentation fault.
0x00007ffff77e9884 in rand () from /lib64/libc.so.6
你能帮帮我吗?
非常感谢。
编辑:这是swapInt函数:
void swapInt (int *a, int *b) {
int aux = *a;
*a = *b;
*b = aux;
}
答案 0 :(得分:1)
程序逻辑中存在错误
例如
在主要
array = [1,2]
调用intArrayQuickSort(array,0,1); // a:array,left:0,right:1
在intArrayQuickSort中
pivot = 1 // rand() % (right - left +1) + left;
的临时结果
call distributePivot(a,0,1,1)
在distributePivot中
不交换(枢轴,右)因为pivot == righit
i = 0 //左
j = 0 //右 - 1
因为i == j
,所以不执行
执行交换(a [i],[右])因为i&lt;对// 0&lt; 1
// a = [2,1] // !! NG
返回0
//已经是非法国家
在intArrayQuickSort中
pivot = 0; //来自返回值:0
调用intArrayQuickSort(a,0,-1); // left:0,pivot -1:-1
没有操作返回
调用intArrayQuickSort(a,1,1); // pivot + 1:1,right:1
没有操作返回
在主要
结果:a = [2,1] // NG!
答案 1 :(得分:0)
其实我找到了一个解决方案,但我不知道为什么会有效。 第二个递归调用应该是:
intArrayQuickSort (a, pivot + 1, right);
这对算法有意义,但我无法理解为什么错误与rand()有关。有什么解释吗?
答案 2 :(得分:0)
我认为
的修改版本int distributePivot (int *a, int left, int pivot, int right) {
int i, j;
if (pivot != right)
swapInt(&a[pivot], &a[right]);
i = left;
j = right - 1;
while (1) {
while (i < right && a[i] < a[right])
i++;
while (left <= j && a[j] >= a[right])
j--;
if (i < j)
swapInt(&a[i], &a[j]);
else
break;
}
if(i < right)
swapInt(&a[i], &a[right]);
return i;
}
void intArrayQuickSort (int *a, int left, int right) {
int pivot;
if (left < right) {
pivot = rand() % (right - left +1) + left ;
pivot = distributePivot(a, left, pivot, right);
intArrayQuickSort (a, left, pivot - 1);
intArrayQuickSort (a, pivot + 1, right);
}
}
答案 3 :(得分:-1)
pivot = rand() % (right - left +1) + left;
应该是:
pivot = left + rand() % (right - left +1);
或者甚至可能:
pivot = left +1 + rand() % (right - left);