Search code examples
cfunctionrecursionquicksort

Quick sort recursive function in C - doesn't work with big number of elements


Has this function been written correctly?

It seems that something is wrong when I try to run the function with a large number of elements in the array (eg 1000).

Then its appears to stop.

int quick_sort(int n, int tablica[],int b, int a)
    {   
        if(a==n-1 || n==0) return;
        if(b==n-1) 
        {
            b=0;
            a++;        
        }

        if(tablica[b]>tablica[b+1])
        {
            bufor=tablica[b];
            tablica[b]=tablica[b+1];
            tablica[b+1]=bufor;
        }
        b++;
        return quick_sort(n,tablica,b,a);
    }

Solution

  • Above code will not work even for a small array, unless the small array is unsorted in a particular way. It compares one element with the next element. If the array is say {4,3,8,7,1} the sort will fail, because it has no mechanism to push 1 to the start of the array.

    For larger arrays there are too many recursion and the program hits the stack limit and simply fails.

    You can use recursion in quicksort but the number of recursions has to be kept in check. For example for array of size 1000 you don't want to have to more than 1000 recursion. Example:

    void swap(int* a, int* b)
    {
        int t = *a;
        *a = *b;
        *b = t;
    }
    
    void quicksort(int arr[], int low, int high)
    {
        if(low < high)
        {
            int pivot = arr[high];    
            int i = (low - 1);  
            for(int j = low; j <= high - 1; j++)
            {
                if(arr[j] <= pivot)
                {
                    i++;    
                    swap(&arr[i], &arr[j]);
                }
            }
            swap(&arr[i + 1], &arr[high]);
            int pi = i + 1;
    
            quicksort(arr, low, pi - 1);
            quicksort(arr, pi + 1, high);
        }
    }
    
    int main()
    {
        int arr[] = { 7,3,6,1,4,8,9,2 };
        int arrsize = sizeof(arr) / sizeof(*arr);
        quicksort(arr, 0, arrsize - 1);
        for(int i = 0; i < arrsize; i++)
            printf("%d\n", arr[i]);
        return 0;
    }