Bryan
Bryan

Reputation: 3009

Quicksort in Java

I'm supposed to do a quicksort algorithm in java to sort the array {50, 20, 65, 30, 75, 25, 90}. Here is what I have so far:

public class QuickSort {
public static int partition(int arrayName[], int down, int up){
    int i = down, j = up;
    int temp;
    int pivot = arrayName[(down + up) / 2];

    while (i <= j){
        while (arrayName[i] < pivot)
            i++;
        while (arrayName[j] > pivot)
            j--;
        if (i <= j){
            temp = arrayName[i];
            arrayName[i] = arrayName[j];
            arrayName[j] = temp;
            i++;
            j--;

        }
    }
    return i;

}
public static void main(String[] args) {
    int [] arrayName = {50, 20, 65, 30, 75, 25, 90};

    System.out.println(partition(arrayName, down, up)); 

}
}

I'm getting an error on the print statement (seem to have a lot of trouble with these) that says down and up cannot be resolved to variables. How can I fix it so I can successfully print the sorted list?

Upvotes: 0

Views: 1687

Answers (3)

user1098888
user1098888

Reputation: 13

you are getting index out of bound ,

because up and down are non initialized and in java it makes them 0

so down goes at j :

while(arrayName[j]<pivot){ //<--- this will thow exception as j starts at 0
  j--;

which leads to -1 and accessing the array at arrayName[-1] is out of bound.

Upvotes: 0

TeaPow
TeaPow

Reputation: 677

Your partition method returns an int. Instead, change your method body so that it returns the newly sorted array (and make sure you change the return type in the method declaration too, else you'll get an error). Furthermore, you need to define up and down in the main method.

For instance:

public static int[] partition(...)
{
...
return arrayname;
}

Edit: furthermore, you may need to use Arrays.toString() to output the array correctly (it's been a while since I used Java). eg:

System.out.println(Arrays.toString(partition(arrayName, up, down)));

Upvotes: 0

Laf
Laf

Reputation: 8205

It's because you haven't defined any variables named down and up in your main method. You should specify values instead of those names.

Upvotes: 6

Related Questions