Search code examples
cquicksort

Quick Sort in C Issue


I'm been stuck at a certain point in my quick sort program in C. Can anybody point out where the error is? My code doesn't run and I've tried comparing it with multiple online programs. I've got a test tomorrow and I want to know what the error is before I attempt it.

#include <stdio.h>

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

int partition(int a[],int l,int h){
    int pi=l,i=l,j=h;
    while(i<j){
            while(a[i]<=a[pi])
                i++;
            while(a[j]>a[pi])
                j--;
            if(i<j){
                swap(a[i],a[j]);
            }
        }
    swap(a[j],a[pi]);
    return j;
}

void quicksort(int a[],int l,int h){
    int j;
    j=partition(a,l,h);
    quicksort(a,l,j-1);
    quicksort(a,j+1,h);
}

int main(){
    int n,i;
    printf("Enter the number of elements: ");
    scanf("%d",&n);
    int a[n];
    printf("Enter the elements: ");
    for(i=0;i<n;i++){
        scanf("%d",&a[i]);
    }
    quicksort(a,0,n-1);
    printf("The array after sorting is: ");
    for(i=0;i<n;i++){
        printf("%d",a[i]);
    }
    return 0;
}

Solution

  • Your code has several issues.

    First, your swap function swaps the local variables a and b, but it won't affect the array a in partition. Ian Abbott has explained this more thoroughly.

    One way to solve that is to pass the addresses of the array elements via pointers, so that swap can access and change them. A simpler way is to write a swap function that operates on indices of an array:

    void swap(int array[], int i, int j)
    {
        int t = array[i]; array[i] = array[j]; array[j] = t;
    }
    

    Second, must stop the recursion at some time. When you have an array with only one element or with no elements at all, there's nothing to do, because the array (or subarray) is already sorted.

    So don't do anything in that case. Or, rather, only do something when you have at least two elements. That has the nice side effect that the recusrion actually stops. :)

    void quicksort(int a[], int l, int h)
    {
        if (l < h) {
            int j;
    
            j = partition(a, l, h);
            quicksort(a, l, j - 1);
            quicksort(a, j + 1, h);
        }
    }