배열에 임의의 숫자가 채워지고 사용자가 위치를 선택하고 프로그램이 배열의 정렬 된 버전에있는 위치와 일치하는 값을 반환하는 임의 선택 알고리즘을 구현하려고합니다. 배열을 실제로 정렬합니다.배열 인덱스가 경계를 벗어났습니다
문제는 프로그램에서 Array Index of Bounds 오류가 발생하고 임의의 파티션 및 스왑 함수를 올바로 작성했다고 생각합니다.
import java.util.*;
public class RandomizedSelection {
public static void main(String[] args) {
int[] arr = new int[10];
// fill array with random numbers between the range of 0-200
for (int i = 0; i < 10; i++) {
int n = (int)(java.lang.Math.random()*199);
arr[i] = n;
}
System.out.println("There is an array of 10 elements in the range" +
" of 0 - 200. Select a location to view" +
" the value.");
int loc = randomizedSelect(arr, 0, arr.length-1, 5);
System.out.println(loc);
System.out.println("The array was:\n" + Arrays.toString(arr));
}
public static int randomizedSelect(int[] array, int start, int end, int i) {
if (start==end)
return array[start];
int q = randomizedPartition(array, start, end);
int k = q - start + 1;
if (i == k)
return array[q];
else if (i < k)
return randomizedSelect(array, start, q-1, i);
else
return randomizedSelect(array, q+1, end, i-k);
}
public static int randomizedPartition(int[] array, int start, int end) {
Random rand = new Random(System.currentTimeMillis());
int pivotIdx = rand.nextInt(end - start + 1) + start;
int pivot = array[pivotIdx];
swap(array, array[pivotIdx], array[end]);
System.out.println(Arrays.toString(array));
pivotIdx = end;
int i = start - 1;
for (int j = start; j <= end-1; j++) {
if (array[j] <= pivot) {
i = i + 1;
swap(array, array[i], array[j]);
}
}
swap(array, array[i+1], array[pivotIdx]);
return i+1;
}
private static void swap(int[] array, int i, int j) {
int temp;
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
인덱스가 범위를 벗어나는 이유를 모르겠습니다. 내 가정은 배열의 마지막 요소에 도달하면이를 바꿀 요소가 없다는 것입니다. 이게 문제 야? 이 문제를 어떻게 해결할 수 있습니까? 나는 그것을 두 개의 배열로 분할하는 것을 생각하고 있었지만 그것을 피하는 것이 좋을 것입니다.
인덱스가 많고 바인딩 검사가 하나도 없습니다. 이것은 특히 배열에 임의 인덱스를 사용할 때의 재난 팩토리입니다. – Maroun
코드를 디버그하여 문제를 쉽게 식별하십시오. – Maroun
경계 검사는 java에서 자동으로 수행됩니다. – Marichyasana