سؤال

I don't know yet what is the problem with the code:

#include <stdio.h>
#define cutoff 3
int swap(int *x, int *y)
{
    int *tmp;
    tmp = x;
    x = y;
    y = tmp;
    return *x, *y;
}
void qsort(int a[], int left, int right)
{
    int i, j;
    int pivot;
    if (left + cutoff <= right) // JUST TO ENSURE THAT THE ARRAY'S SIZE IS >= CUTOFF.
    {
        pivot = median(a, left, right);
        i = left;
        j = right - 1;
        for (;;)
        {
            while (a[i] < pivot)
                i++;
            while (a[j] > pivot)
                j--;
            if (i < j)
                swap(&a[i], &a[j]);
            else
                break;
        }
        swap(&a[i], &a[right - 1]); // RESTORE PIVOT
        qsort(a, left, i-1);
        qsort(a, i+1, right);
    }
    //else
        // PERFORM INSERTION SORT
}
void quicksort(int a[], int n)
{
    int i;
    qsort(a, 0, n - 1);
    printf("THE SORTED ARRAY IS: ");
    for(i=0;i<n;i++)
        printf("%d ", a[i]);
}
int median(int a[], int left, int right)
{
    int center = (left + right) / 2;
    if(a[left] > a[center])
        swap(&a[left], &a[center]); 
    if(a[left] > a[right])
        swap(&a[left], &a[right]);
    if(a[center] > a[right])
        swap(&a[center], &a[right]);
    swap(&a[center], &a[right - 1]); // HIDE PIVOT.
    return a[right - 1]; // RETURN PIVOT.
}
void main()
{
    int a[100], i, n;
    printf("ENTER THE SIZE: ");
    scanf("%d", &n);
    printf("ENTER THE UNSORTED ARRAY: ");
    for (i=0;i<n;i++)
        scanf("%d", &a[i]);
    quicksort(a, n);        
}

The output is the same as teh input and soemtimes it is taking more than the input size. I think that the problem lies in the median function, choosing the pivot.

هل كانت مفيدة؟

المحلول

int swap(int *x, int *y)
{
    int *tmp;
    tmp = x;
    x = y;
    y = tmp;
    return *x, *y;
}

You're assigning the pointers, not their values. Use this instead

void swap(int *x, int *y)
{
    int tmp;
    tmp = *x;
    *x = *y;
    *y = tmp;
}

Also, the return means nothing since the values are swapped by the pointers, and you cannot also return 2 values at a time. The return type should be void like @Yu Hao said

نصائح أخرى

The main problem is in your swap() function

int swap(int *x, int *y)
{
    int *tmp;
    tmp = x;
    x = y;
    y = tmp;
    return *x, *y;
}

It only swaps the value of the pointer x and y themselves, but not the value that x and y points. Remember that functions in C are always pass-by-value. You need to swap *x and *y.

void swap(int *x, int *y)
{
    int tmp;
    tmp = x;
    *x = *y;
    *y = tmp;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top