简体   繁体   中英

Hybrid QuickSort + Insertion sort java.lang.StackOverflowError

I am trying to calculate the running time of hybrid quickSort - insertionSort. However, when presented with a larger array (~500k elements), I get a java.lang.StackOverflowError. Can I somehow overcome this? Not using recursion is not an option.

Here's the code:

public class QuickSort2 {

private static void swap(int[] arr, int x, int y){
       int temp = arr[x];
       arr[x] = arr[y];
       arr[y] = temp;
    }

private static int partition(int[] arr, int lo, int hi){
    int pivot = arr[hi];
    int index = lo - 1;
    for(int i = lo; i < hi; i++){
        if(arr[i] < pivot){
            index++;
            swap(arr, index, i);
        }
    }
    swap(arr, index + 1, hi);
    return index + 1;
} 

public static void quickSort(int[] arr, int lo, int hi){
    if(lo < hi && hi-lo > 10){
        int q = partition(arr, lo, hi);
        quickSort(arr,lo,q-1);
        quickSort(arr,q+1,hi);
        }else{
            InsertionSort.insertSort(arr);
        }    
    }
}

and also, the insertionSort:

public class InsertionSort {

static void insertSort(int[] arr){
    int n = arr.length;
    for (int j = 1; j < n; j++){
        int key = arr[j];
        int i = j-1;
        while ((i >= 0) && (arr[i] > key)){
            arr[i+1] = arr[i];
            i--;
        }
        arr[i+1] = key;
    }         
}

The lines where the error occurs:

quickSort(arr,lo,q-1);
quickSort(arr,q+1,hi);

and also the calling code:

public class RunningTime {

public static void main(String[] args) {
    int[] arr = ReadTest.readToArray("int500k");
    int lo = 0;
    int hi = arr.length - 1;

    long startTime = System.currentTimeMillis();
    QuickSort2.quickSort(arr, lo, hi);
    long stopTime = System.currentTimeMillis();
    long elapsedTime = stopTime - startTime;
    System.out.println("Running time: " + elapsedTime);
    System.out.println("Array is sorted: " + isSorted(arr));
}

}

You should restrict insertion sort to work only on the subset of the array.

Besides this, I don't see any other issues with your code.

Is the file int500k sorted? If so this is the worst case scenario for quick sort, which means that the recursion will be 500k levels deep.

To fix it you can for instance choose the pivot randomly instead of arr[hi] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM