简体   繁体   中英

My quicksort algorithm is giving me a trace trap, how can I fix it?

So currently I am trying to make a quicksort algorithm for an array of strings (to sort them alphabetically) since I can't use the qsort() function for this exercise and I also cannot allocate memory ( malloc() , etc). So, I tried to do it recursively. After testing the first time it worked but as I added more text to the array, it now throws a trace trap which I don't know how to fix.

#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);

    }
}

The way I call it is pretty simple:

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]);
    }
}

However this throws a trace trap.

If someone could help me find out what is wrong and fix it that would be great!!

Thank you.

The problem is that you're swapping the value with itself here:

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

I believe:

i = start + 1;

would be a slight optimization, and together with

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

would be sufficient fix.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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