我试图在Java中递归地实现选择排序,但是我的程序不断抛出ArrayIndexOutOfBounds异常。不知道我在做什么错。递归对我来说很难。请帮忙!我是初学者。
public static int[] selection(int[] array) {
return sRec(array, array.length - 1, 0);
}
private static int[] sRec(int[] array, int length, int current) {
if (length == current) { //last index of array = index we are at
return array; //it's sorted
}
else {
int index = findBig(array, length, current, 0);
int[] swapped = swap(array, index, length - current);
return sRec(swapped, length - 1, current);
}
}
private static int[] swap(int[] array, int index, int lastPos) {
int temp = array[lastPos];
array[lastPos] = array[index];
array[index] = array[temp];
return array;
}
private static int findBig(int[] array, int length, int current, int biggestIndex) {
if (length == current) {
return biggestIndex;
}
else if (array[biggestIndex] < array[current]) {
return findBig(array, length, current + 1, current);
}
else {
return findBig(array, length, current + 1, biggestIndex);
}
}
public static void main (String [] args) {
int[] array = {8,3,5,1,3};
int[] sorted = selection(array);
for (int i = 0; i < sorted.length; i++) {
System.out.print(sorted[i] + " ");
}
}
答案 0 :(得分:2)
尝试通过Swap方法更改此内容:
int temp = array[lastPos];
array[lastPos] = array[index];
array[index] = array[temp];
return array;
对此:
int temp = array[lastPos];
array[lastPos] = array[index];
array[index] = temp;
return array;
您已经获得了要分配给数组的值,将其添加到数组时,它将在该特定索引中进行搜索,
例如:
您想为数组输入值8
代替
array[index] = 8
你在做
array[index] = array[8]
这导致您的OutOfBounds异常。
答案 1 :(得分:0)
我测试了您的代码,即使修复了“ Out Of bound Exception”,它也没有排序。我已经更改了您的方法findBig以便使其工作。原理是:
这将导致以下代码按降序对数组进行排序:
public class Sort {
public static int[] selection(int[] array) {
return sRec(array,0);
}
private static int[] sRec(int[] array, int current) {
if (current == array.length-1) { //last index of array = index we are at
return array; //it's sorted
}
else {
int indexOfBiggest = findBig(array, current,array.length-1);
int[] swapped = swap(array, indexOfBiggest, current );
return sRec(swapped, current+1);
}
}
private static int[] swap(int[] array, int index, int lastPos) {
int temp = array[lastPos];
array[lastPos] = array[index];
array[index] = temp;
return array;
}
private static int findBig(int[] array, int begin, int end) {
if (begin < end) {
int middle = (begin+end)/2;
int biggestLeft = findBig(array,begin,middle);
int biggestRight = findBig(array,middle+1,end);
if(array[biggestLeft] > array[biggestRight]) {
return biggestLeft;
}else {
return biggestRight;
}
}else {
return begin;
}
}
public static void main (String [] args) {
int[] array = {8,3,5,1,3};
// System.out.println(findBig(array,0,array.length-1));
int[] sorted = selection(array);
for (int i = 0; i < sorted.length; i++) {
System.out.print(sorted[i] + " ");
}
}
}