繁体   English   中英

我的快速排序算法给了我一个跟踪陷阱,我该如何解决?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM