Thread: Need help with quick sort algorithm

  1. #1
    Registered User
    Join Date
    Nov 2013
    Posts
    4

    Need help with quick sort algorithm

    Hello

    I tried to program a quick sort algorithm with a pre-defined array. As I was ready and tried to run the program I got a stack overflow.

    Can someone help me with this problem and maybe tell me the cause?

    Code:
    #include <conio.h>
    #include <stdio.h>
    #include <stdlib.h>
    
    int partition(int *A, int start, int end)
    {
        int i, hilf;
        int pivot;
        int pIndex;
        pivot = A[end];
        pIndex = start;
    
        for(i=start; i<end; i++)
        {
            if(A[i]<=pivot)
            {
                hilf=A[pIndex];
                A[pIndex]=A[i];
                A[i]=hilf;
                pIndex++;
            }
        }
        hilf=A[pIndex];
        A[pIndex]=A[end];
        A[end]=hilf;
    }
    
    void sort (int *A, int start, int end)
    {
        int pIndex;
        pIndex = partition(A, start, end);
        sort(A, start, pIndex-1);
        sort(A, pIndex+1, end);
        return;
    }
    
    int main()
    {
        int i;
        int A[] = {7,3,2,6,4,1,5,8};
        sort(A,0,7);
    
        for(i=0;i<8;i++)
            printf("%4d", A[i]);
        getch();
        return 0;
    }

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Every recursion must have a base case -- as it stands you call sort, which calls sort twice, which calls sort four times, which calls sort eight times, which ...... You'll need to decide when you are "done" with a subarray.

  3. #3
    Registered User
    Join Date
    Nov 2013
    Posts
    4
    Quote Originally Posted by tabstop View Post
    Every recursion must have a base case -- as it stands you call sort, which calls sort twice, which calls sort four times, which calls sort eight times, which ...... You'll need to decide when you are "done" with a subarray.
    Thanks a lot

    Code:
    void sort (int *A, int start, int end)
    {
        int pIndex;
        if (start < end)
        {
        pIndex = partition(A, start, end);
        sort(A, start, pIndex-1);
        sort(A, pIndex+1, end);
        }
        return;
    }
    That was the missing condition.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 10
    Last Post: 05-31-2012, 01:11 AM
  2. Help me on Quick Sort algorithm
    By chatterjee in forum C Programming
    Replies: 21
    Last Post: 07-19-2009, 01:40 PM
  3. Quick Sort or Merge Sort???
    By swanley007 in forum C++ Programming
    Replies: 6
    Last Post: 11-10-2005, 06:48 PM
  4. Quick sort VS Merge Sort
    By sachitha in forum Tech Board
    Replies: 7
    Last Post: 09-03-2004, 11:57 PM
  5. Shell Sort vs Heap Sort vs Quick Sort
    By mackol in forum C Programming
    Replies: 6
    Last Post: 11-22-2002, 08:05 PM