0

I am implementing a quicksort and i am getting stackoverflow error.I have tried muliple times and getting frustrated by seeing this error.Can anyone please help me guys

import java.util.Arrays;

public class QuickSort {

public static void main(String[] args) {
    int[] arr = { 5, 7, 6, 1, 3, 2, 4 };
    int lowerIndex = 0;
    int higherIndex = arr.length - 1;

    quickSort(arr, lowerIndex, higherIndex);

    System.out.println(" FiNaLly " + Arrays.toString(arr));

}

private static void quickSort(int[] arr, int lowerIndex, int higherIndex) {

    int pivot = arr[arr.length - 1];
    int i = 0;
    int temp = 0;
    int middle = arr.length / 2;
    for (int j = 0; j < arr.length - 1; j++) {
        if (arr[j] < pivot) {
            temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
            i++;
        }
        if (i == middle) {
            int swap = arr[middle];
            arr[middle] = arr[arr.length - 1];
            arr[arr.length - 1] = swap;
        }

    }
    int q = Arrays.binarySearch(arr, pivot);


    if (higherIndex > lowerIndex) {
        quickSort(arr, 0, q - 1);
    }
      if(q<arr.length-1){
          quickSort(arr, q+1, arr.length-1);
      }

}

}

prasad
  • 63
  • 2
  • 9
  • 4
    Well you unconditionally call `quicksort` at the end of its implementation, so it will obviously result in an endless recursion, which causes the stack overflow. – flyx Feb 17 '17 at 10:53
  • so you mean to say i should call at the end of the method instead calling in the method right? – prasad Feb 17 '17 at 10:54
  • 1
    I mean that you should review your program logic. There are too many problems here to provide a good answer. For example, you completely ignore the parameters `lowerIndex` and `higherIndex`. The recursive call should only be executed if some condition is true so that the program terminates. – flyx Feb 17 '17 at 10:56
  • 1
    Add an 'if' condition inside the quicksort method and outside for loop which will return something if the difference in length is 1 or 2 thus ending the recursion. This is the most important thing to remember when doing recursion to prevent stackoverflow error. – Abhishek J Feb 17 '17 at 10:57
  • if(higherIndex>lowerIndex){ quickSort(arr, 0, q - 1); } i have added this condition in one of the two call .if should sort atleast the left side of the array.but it is not getting sorted :( – prasad Feb 17 '17 at 11:01
  • The short answer, a recursive loop without an exit condtion is an endless loop – AxelH Feb 17 '17 at 11:16
  • i have added the if condition but then it is still giving me the same error' – prasad Feb 17 '17 at 12:15

0 Answers0