【问题标题】:My quicksort algorithm is giving me a trace trap, how can I fix it?我的快速排序算法给了我一个跟踪陷阱,我该如何解决?
【发布时间】:2021-07-06 21:49:12
【问题描述】:

所以目前我正在尝试为字符串数组创建一个快速排序算法(按字母顺序排序),因为我不能在这个练习中使用 qsort() 函数,我也不能分配内存(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]);
    }
}

但是这会引发跟踪陷阱。

如果有人能帮我找出问题所在并修复它,那就太好了!

谢谢。

【问题讨论】:

  • minimal reproducible example 请。 IE。一个完整的最小程序,带有一个你调用它的主函数,包括等等。
  • @AnttiHaapala 在调用中添加了 main 函数,还添加了 include。

标签: c string algorithm sorting quicksort


【解决方案1】:

问题是你在这里与自己交换值:

swap(array[pivot], array[j]);

我相信:

i = start + 1;

会稍微优化一下,和一起

if (pivot != j) {
    swap(array[pivot], array[j]);       
}

就足够了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-06
    • 2010-10-20
    • 2021-08-18
    • 1970-01-01
    • 2017-09-26
    • 1970-01-01
    • 1970-01-01
    • 2017-02-15
    相关资源
    最近更新 更多