Hello everyone,
I have some code to sort a random array of integers, although im getting an error whenever I try to run the method. It prints the input and then I get an error. The code is below and the error is below that.
If anyone could help me that would be great!
import java.util.Random;
public class quickSort{
public static void main(String a[]){
long start, end, total;
start = System.nanoTime();
Random r = new Random();
int i;
int [] array = new int [100];
for (int k = 0; k < array.length; k++){
array[k] = (r.nextInt(1000)+1);
}
System.out.print("Quick Sort Algorithm");
System.out.print("\n\nInput: ");
for(i = 0; i < array.length; i++)
System.out.print( array[i]+" ");
quicksort(array,0, array.length);
System.out.print("\n\nOutput: ");
for(i = 0; i < array.length; i++)
System.out.print(array[i]+" ");
end = System.nanoTime();
total = end - start;
System.out.print("\n\nTime to execute = "+total+" nanoseconds\n\n");
}
public static void quicksort (int array[], int lo, int hi)
{
int i=lo, j=hi, h;
int x=array[(lo+hi)/2];
do
{
while (array[i]<x) i++;
while (array[j]>x) j--;
if (i<=j)
{
h=array[i]; array[i]=array[j]; array[j]=h;
i++; j--;
}
} while (i<=j);
if (lo<j) quicksort(array, lo, j);
if (i<hi) quicksort(array, i, hi);
}
}
java.lang.ArrayIndexOutOfBoundsException: 100
at quickSort.quicksort(quickSort.java:32)
at quickSort.main(quickSort.java:16)
Thanks in advance