I am working on a program that uses quick sort to sort an array to display the running time. This program selects the median of three random numbers as the pivot. However, I am not sure if I am doing something wrong because every time I run this program I get the following errors:
"java.lang.StackOverflowError",
at java.util.Random.nextInt(Unknown Source)
at SortingItems.quickSort(SortingItems.java:31)
at SortingItems.quickSort(SortingItems.java:69) " I get this specific message multiple times"
This is the code:
import java.util.Random;
public class SortingItems {
static int x = 1000;
static int array [] = new int[x];
public static void main(String[] args) {
long time;
input(x, array);
time = System.nanoTime();
sort(array);
System.out.println("Running time in ascending order " + (System.nanoTime() - time));
}
public static void sort(int[] array) {
quickSort(array, 0, array.length - 1);
}
public static void quickSort(int[] array, int low, int high) {
if (array == null || array.length == 0)
return;
if (low >= high)
return;
// Generating random numbers from 0 to the last element of the array
Random f = new Random();
int first = f.nextInt(array.length - 1);
Random s = new Random();
int second = s.nextInt(array.length - 1);
Random t = new Random();
int third = t.nextInt(array.length - 1);
// Selecting the pivot
int pivot = Math.max(Math.min(array[first], array[second]),
Math.min(Math.max(array[first],array[second]), array[third]));
int i = low;
int j = high;
while (i <= j) {
while (array[i] < pivot) {
i++;
}
while (array[j] > pivot) {
j--;
}
if (i <= j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
i++;
j--;
}
}
if (low < j)
quickSort(array, low, j);
if (high > i)
quickSort(array, i, high);
}
// Input in ascending order
public static int[] input(int x, int[] array) {
for (int k = 0; k < x; k++) {
array[k] = k;
}
return array;
}
}