Click here to Skip to main content
15,886,799 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hey
i am still a beginner at programming but i am trying to write a program that counts the number of comparisons in a quicksort program


this is my code


package algo_quicksort;

public class Algo_quicksort {

    public static int partition(int[]A,int p,int r){
        int x=A[p];
        int i=p+1;
        int temp;
        for(int j=p+1;j<r;j++){
            if(A[j]<x){//if A[j] is bigger than the pivot do nothing 
                temp=A[j];
                A[j]=A[i];
                A[i]=temp;
                i++;
            }
        }
        temp=A[p];
        A[p]=A[i-1];
        A[i-1]=temp;
        return i-1;
    }
    public static long quickSort(int[]A,int startPos,int length){
        if(length==1){
            return 0;
        }
        else{
            if(startPos<length){
            int pivot= partition(A,0,length);
          quickSort(A,startPos,pivot+1);
          quickSort(A, pivot+2,length); 
            return length-startPos-1;
        }
            else{
                return 0;
            }
    }
    }
    
    
    public static void main(String[] args) {
        int a[]={3,2,4};
        System.out.println("# of comparisons is: " +quickSort(a,0,a.length));

        System.out.println("A[] after quicksort is: ");
        
        for(int i=0;i<a.length;i++){
            System.out.print(a[i]+"  ");
        }

    }
}


it works perfectly for any array of size 3 or less
but if it is any bigger than that it gives me a stackoverflow exception at the recursive call
i tried debugging my code but could not figure out where it's going wrong
i would appreciate any help i get ^_^
Posted
Comments
pasztorpisti 5-Aug-13 16:40pm    
Your quicksort is simply buggy in many places. Why don't you copy someone else' quicksort implementation: http://www.algolist.net/Algorithms/Sorting/Quicksort
Maciej Los 5-Aug-13 17:06pm    
Why don't you posted it as an answer?
pasztorpisti 5-Aug-13 17:17pm    
I thought it was too simple stupid for that. :-)
Richard C Bishop 5-Aug-13 18:33pm    
Perhaps, but it would remove this post from the queue of unanswered questions.
pasztorpisti 5-Aug-13 18:53pm    
Done. :-)

1 solution

Your quicksort is simply buggy in many places. Why don't you copy someone else' quicksort implementation: http://www.algolist.net/Algorithms/Sorting/Quicksort[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900