[英]My quicksort algorithm is giving me a trace trap, how can I fix it?
所以目前我正在嘗試為字符串數組(按字母順序排序)創建一個快速排序算法,因為我不能使用 qsort() function 進行這個練習,我也不能分配 memory ( malloc()
等)。 所以,我試着遞歸地做。 在第一次測試它工作后,但當我向數組添加更多文本時,它現在拋出一個我不知道如何修復的跟蹤陷阱。
#include <stdio.h>
#include <string.h>
void swap(char a[], char b[])
{
char temp[51];
strcpy(temp, a);
strcpy(a, b);
strcpy(b, temp);
}
void quicksort(char array[10000][51], int start, int end)
{
int i, j, pivot;
if( start < end )
{
pivot = start;
i = start;
j = end;
while( i < j)
{
/* i & pivot */
while( (strcmp(array[i], array[pivot]) <= 0) && i < end )
i++;
/* j & pivot */
while( (strcmp(array[j], array[pivot]) > 0) )
j--;
if( i < j )
{
swap(array[i], array[j]);
}
}
swap(array[pivot], array[j]);
quicksort(array, start, j - 1);
quicksort(array, j + 1, end);
}
}
我稱它的方式很簡單:
int main()
{
int i;
char input[10000][51] = {"this is a test", "another", "fffff", "a" , "skjfkdjf"};
quicksort(input, 0, 4);
/* used to print the strings */
for(i = 0; i < 5; i++)
{
printf("%s\n", input[i]);
}
}
但是,這會引發跟蹤陷阱。
如果有人可以幫助我找出問題所在並修復它,那就太好了!
謝謝你。
問題是您在這里與自身交換值:
swap(array[pivot], array[j]);
我相信:
i = start + 1;
將是一個輕微的優化,並與
if (pivot != j) {
swap(array[pivot], array[j]);
}
就足夠了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.