I need to sort the array through this array of indexes. I don't understand why I have
Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.
I also can't sort it with quicksort. I guess it's because I have an issue with curly braces?
public static void main(String[] args) {
int[] arr = {4, 3, 6, 2, 5};
Integer[] index = new Integer[arr.length];
{
for (int i = 0; i < 10; i++) {
{
index[i] = i;
}
System.out.print(String.format("%d, ", arr[index[i]]));
System.out.println(Arrays.toString(index));
}
int low = 0;
int high = index.length;
quickSort(index, low, high);
System.out.println(Arrays.toString(index));
}
}
public static void quickSort (Integer[]index ,int low, int high){
if (low >= high)
return;
// берем pivot
int middle = low + (high - low) / 2;
int pivot = index[middle];
// лево меньше pivot и право больше pivot
int i = low, j = high;
while (i <= j) {
while (index[i] < pivot) {
i++;
}
while (index[j] > pivot) {
j--;
}
if (i <= j) {
int temp = index[i];
index[i] = index[j];
index[j] = temp;
i++;
j--;
}
}
// рекурсируем две саб части
if (low < j)
quickSort(index, low, j);
if (high > i)
quickSort(index, i, high);
}
}
4, [0, null, null, null, null]
3, [0, 1, null, null, null]
6, [0, 1, 2, null, null]
2, [0, 1, 2, 3, null]
5, [0, 1, 2, 3, 4]
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at Arr.main(Arr.java:10)