So this is my code. The error is ArrayIndexOutOfBoundsException
, below I have mentioned it. Please help me find the cause.
import java.util.Scanner;
public class sort {
public static void main(String args[]){
Scanner s = new Scanner(System.in);
System.out.println("Enter the number of entries");
int[] arr = new int[s.nextInt()];
System.out.println("Enter the numbers");
for(int i=0;i<arr.length;i++)
arr[i] = s.nextInt();
s.close();
QuickSort.sort(arr);
for(int i=0;i<arr.length;i++)
System.out.print(arr[i]+" ");
}
}
public class QuickSort {
private static int partition(int[] arr, int hi, int lo){
int i=lo,j=hi+1,swap=0;
while(true){
while(arr[++i]<arr[lo])
if(i==hi)break;
while(arr[--j]>arr[lo]) \\error line
if(j==lo)break;
if(j<=i)break;
swap=arr[i];
arr[i]=arr[j];
arr[j]=swap;
}
swap=arr[lo];
arr[lo]=arr[j];
arr[j]=swap;
return j;
}
public static void sort(int[] arr){
sort(arr,arr.length-1,0);
}
private static void sort(int[] arr,int hi,int lo){
int j = partition(arr,hi,lo);
sort(arr,j-1,lo);
sort(arr,hi,j+1);
}
}
Error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 at riku.QuickSort.partition(QuickSort.java:10) at riku.QuickSort.sort(QuickSort.java:28) at riku.QuickSort.sort(QuickSort.java:29) at riku.QuickSort.sort(QuickSort.java:29) at riku.QuickSort.sort(QuickSort.java:29) at riku.QuickSort.sort(QuickSort.java:25) at riku.sort.main(sort.java:12) this is the complete error log