【发布时间】:2014-11-11 09:02:02
【问题描述】:
我必须根据这些参数在 Java 中实现选择排序:
对 SelectionSort 实施一种变体,在扫描列表时定位最小和最大元素,并将它们分别定位在列表的开头和结尾。在第一次通过时,元素 x0,...,xn-1 被扫描;在第二遍中,元素 x1,...,xn-2 被扫描;等等。
我向方法传递了一个大小为 32 的数组,当我打印该数组时,它没有排序。我的代码有什么问题?
static void selectionSort() {
scramble();
int smallIndex = 0; //index of smallest to test
int largeIndex = array.length - 1; //index of largest to test
int small = 0; //smallest
int large; //largest
int smallLimit = 0; //starts from here
int largeLimit = array.length - 1; //ends here
int store; //temp stored here
int store2;
for(int i = 0; i < array.length/2; i++) { //TODO not working...
small = array[smallLimit];
large = array[largeLimit];
for(int j = smallLimit; j <= largeLimit; j++) {
if(array[j] < small) {
smallIndex = j;
small = array[j];
}
else if(array[j] > large) {
largeIndex = j;
large = array[j];
}
}
store = array[smallLimit];
store2 = array[smallIndex];
array[smallLimit] = store2;
array[smallIndex] = store;
store = array[largeLimit];
array[largeLimit] = array[largeIndex];
array[largeIndex] = store;
smallLimit++;
largeLimit--;
}
print();
}
【问题讨论】:
-
参见 J.B. Hayfron-Acquah、Obed Appiah K. Riverson:“改进的选择排序算法”以获取参考(以及改进的 O(n) 空间选择排序)。重复“Selection sort modified”,或多或少。
标签: java arrays sorting selection-sort