-1

I am trying to grasp a better understanding of the Quick Sort Algorithm I understand what happens underneath the code.

But when I write it I am getting the famous java.lang.ArrayIndexOutOfBoundsException.

I can not see where and have been messing around with the indexes of the arrays for sometime now but to no avail.

Here is my code

package QuickSort;

public class quickSort {


    public static void main(String[] args) {
        int[] array = {9,4,6,3,7,1,2,11,5};
        printArray(array);

    //10    sort(array, 0, array.length - 1);


    }

    //Partition Method Algorithm 
    static int partition(int arr[], int start, int end) {

        //Start pivot at the last Index
        int pivot = arr[end];

        //The partition index checks if the number which was last switched 
//19    int partitionIndex = start;

        for(int i = start; start < end; i++) {

            if(arr[i] <= pivot) {

                int temp = arr[i];              
                arr[i] = arr[partitionIndex];             
                arr[partitionIndex] = temp;

                partitionIndex++;
            }

        }

        int temp = arr[partitionIndex];
        arr[partitionIndex] = end; 
        arr[end] = temp;


        return partitionIndex;


    }

    //Recursive function:
    //piviotIndex is returned and keeps track of where the partition ends for the LHS
    //PivotIndex keeps track of where the RHS partition starts 
    static void sort(int arr [], int start, int end) {
        if(start<end) {
    //52    int pivotIndex = partition(arr, 0, end);
        partition(arr, start, pivotIndex-1);
        partition(arr, pivotIndex+1, end);      
        }

    }

    static void printArray(int arr[]) {
        for(int i : arr)
            System.out.print(i + ", ");
    }
}

The error message I am getting is

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
    at QuickSort.quickSort.partition(quickSort.java:19)
    at QuickSort.quickSort.sort(quickSort.java:52)
    at QuickSort.quickSort.main(quickSort.java:10)
Liam
  • 568
  • 2
  • 15

2 Answers2

1

Change

for(int i = start; start < end; i++) {

to

for(int i = start; i < end; i++) {
wings
  • 791
  • 6
  • 21
0

If you really want to check start < end condition then you could do something like this in your forloop, to avoid ArrayIndexOutOfBoundsException exception

for(int i = start; i < end && start < end; i++) 
or if not then
for(int i = start; i < end ; i++)

But I could see still your code is not printing sorted array

MOnkey
  • 751
  • 6
  • 13