Quicksorting a string array in Java?

Viewed 94

Complete Java newbie so please forgive any silly mistakes. I'm working on a larger assignment but have gotten stuck on a quicksort method and despite playing with it for the last few hours and looking at it til I've almost gone blind, I can't seem to figure out where I'm going wrong.

I'm getting an error message "error: method QuicksortString in class testmenu01 cannot be applied to given types". I know that this is something to do with how I've passed parameters in, but have tried and retried and cannot find my mistake. I'm sure its something silly and glaringly obvious, but cannot find it. Would really appreciate any help, thanks!

public class testmenu01 {

public static void main(String[] args){
    String[] nameArr = {"Anna", "Brad", "Charles", "Debbie", "Emma", "Fergal"};
    QuicksortString( nameArr );


}

public void QuicksortString(String [] stringArray, int start, int end) {
    int i = start;
    int k = end;
    if (end - start >= 1) {
        String pivot = stringArray[start];
        while (k > i) {
            while (stringArray[i].compareTo(pivot) <= 0 && i <= end && k > i)
                i++;
            while (stringArray[k].compareTo(pivot) > 0 && k >= start && k >= i)
                k--;
            if (k > i)
                swap(stringArray, i, k);
        }
        swap(stringArray, start, k);
        QuicksortString(stringArray, start, k - 1);
        QuicksortString(stringArray, k + 1, end);
    } else { return; }
}
public void swap(String array[], int index1, int index2) {
    String temp = array[index1];
    array[index1] = array[index2];
    array[index2] = temp;
}

}

1 Answers

To fix the error, changing QuicksortString( nameArr ); in the main method into QuicksortString( nameArr, 0,nameArr.length-1 ); since you defined this method with a parameter list of three parameters:public void QuicksortString(String [] stringArray, int start, int end). Just like your recursive call.

Besides, you'd better change to another line for the return in the elseclause:

else { 
    return; 
}

And it should be a static method for both swap and QuicksortString(quicksortStringis a better method name in java) to let the static method main call them without instantiating the class.

Related