今天我正在学习 R.Sedgewick 的 Algorithms in C 中的快速排序算法。
我对算法的工作原理有了很大的了解。编码部分让我有点困惑,最后我遇到了分段错误。这是代码:
#include <stdio.h>
void quicksort(int[], int, int); // prototype
void quicksort(int a[], int l, int r) // What is the value of l. Why hasn't the author
// mentioned it. Is it the size of the array?
{
int i, j, v, t;
if(r > l)
{
v = a[r];
i = l - 1; // What is l here? Is it the size if yes look at first while statement
j = r;
for(;;)
{
/*The algorithm says: scan from right until an element < a[r] is found. Where
r is the last position in the array. But while checking in the second while
loop elements > a[r] is searched */
while (a[++i] < v); // How can you increment again after reaching end of arrray
// size if l is the size of the array
while (a[--j] > v);
if(i >= j) break;
t = a[i]; a[i] = a[j]; a[j] = t;
}
}
t = a[i]; a[i] = a[r]; a[r] = t;
quicksort(a, l, i - 1);
quicksort(a, i + 1, r);
return;
}
int main()
{
int i, a[10]; // assuming size is 10
for(i = 0; i < 10; i++)
{
scanf("%d", &a[i]);
}
int l = 10; // I am passing size of the array
int r = 9; // position of last element
quicksort(a, l, r);
return 0;
}
错误是这样的。假设如果我输入 10 个元素然后按 Enter,会发生以下情况:
1 4 8 2 3 6 4 7 10 9
segmentation fault.
process returned 139(0x8b)
这是调试器返回的:
Breakpoint 1, quicksort (a=0xbffff808, l=0, r=0) at quick.c:11
11 if(r > 1)
(gdb) c
Continuing.
Program received signal SIGSEGV, Segmentation fault.
0x080484fb in quicksort (a=0xbffff808, l=0, r=0) at quick.c:28
28 t = a[i]; a[i] = a[r]; a[r] = t;
(gdb) c
Continuing.
Program terminated with signal SIGSEGV, Segmentation fault.
The program no longer exists.
(gdb) c
The program is not being run.
执行上述程序的正确方法是这样。左右指针什么都没有。如果数组占用 n 个内存位置,则左指针应指向第 0 个位置,右指针应指向 n - 1 个位置。我犯了一个愚蠢的错误,没有在 if 条件中包含快速排序的递归函数。因此,所有的头痛。正确的程序是:
/* Working quicksort
* Robert sedgewick best
*/
#include <stdio.h>
void quicksort(int[], int, int); // prototype
void quicksort(int a[], int l, int r)
{
int i, j, v, t;
if(r > l)
{
v = a[r];
i = l - 1;
j = r;
for(;;)
{
while (a[++i] < v);
while (a[--j] > v);
if(i >= j) break;
t = a[i]; a[i] = a[j]; a[j] = t;
} // End for here
t = a[i]; a[i] = a[r]; a[r] = t;
quicksort(a, l, i - 1);
quicksort(a, i + 1, r);
} /* End if here. That is include the recursive
functions inside the if condition. Then it works
just fine. */
return;
}
int main()
{
int i, a[5]; // assuming size is 10
for(i = 0; i < 5; i++)
{
scanf("%d", &a[i]);
}
int l = 0; // I am passing size of the array
int r = 4; // position of last element
quicksort(a, l, r);
int s;
for(s = 0; s < 5; s++)
{
printf("%d ", a[s]);
}
return 0;
}