Pregunta

I wrote this lomuto-type function to use for quick sort, but it didn't work. Segmentation fault occurred in run-time. Where is my mistake?

int partition(int *a, int low, int high)
{
    int pos = low, i, pivot = a[low], temp;

    for (i = low + 1; i <= high; i++)
        if(a[i] <= pivot) {
            pos++;
            temp = a[pos];
            a[pos] = a[i];
            a[i] = temp;
        }

    return pos;
}

void quickS(int *a, int low, int high)
{
    while (low < high) {
        int pivot =  partition(a, low, high);
        quickS(a, low, pivot - 1);
        low = pivot + 1;
    }
}
¿Fue útil?

Solución

pivot(a[low]) seems to be there is a need to exchange.

Code for verification:

#include<stdio.h>

int partition(int *a, int low, int high){
    int pos = low, i, pivot = a[low], temp;
    for (i = low + 1; i <= high; i++)
        if(a[i] <= pivot) {
            pos++;
            temp = a[pos];
            a[pos] = a[i];
            a[i] = temp;
        }
    return pos;
}

int main(){
    int data[] = { 10, 1, 2, 3 };
    int i, retvalue;
    retvalue = partition(data, 0, 4-1);
    printf("%d\n", retvalue);
    for(i = 0; i< 4; ++i)
        printf("%d ", data[i]);//10 1 2 3 : N/C 
    printf("\n");
    return 0;
}

It is believed that if the partition function such suspect that the cause a stack overflow, and then repeat the call does not work correctly.

Otros consejos

Try this:

void swap(int *a, int *b) 
{
    int temp = *a;
    *a = *b;
    *b = temp; 
}

int partition(int data[], int l, int h) 
{
    int i;
    int p;
    int firsthigh;

    p = h;
    firsthigh = l;

    for (i = l; i < h; ++i)
    {
        if (data[i] < data[p])
        {
            swap(&data[i], &data[firsthigh]);
            firsthigh++;
        }
    }

    swap(&data[p], &data[firsthigh]);

    return firsthigh; 
}

try like this

 int partition (int arr[], int low, int high )
        {
            int x = arr[high];
            int i = (low - 1);

            for (int j = l; j <= high- 1; j++)
            {
                if (arr[j] <= x)
                {
                    i++;
                    swap (&arr[i], &arr[j]);
                }
            }
            swap (&arr[i + 1], &arr[high]);
            return (i + 1);
        }
void quickSort(int A[], int low, int high)
{
    if (low < high)
    {        
        int p = partition(A, low, high);
        quickSort(A, low, p - 1);  
        quickSort(A, p + 1, high);
    }
}

After you get the correct position of the pivot, you need to place the pivot in that position and then return the position.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top