我是Java的初学者,目前我正在阅读一本名为"Java编程简介"的书.在页276上有一个Array上的Selection排序示例.我坐在这里试图解决它几个小时,我只是不理解它.我理解这个代码是按升序排序数组但是如果有人能够更详细地解释代码的不同部分是什么,我将不胜感激完全做.
double[] list = { 1, 9, 4.5, 6.6, 5.7, -4.5 };
SelectionSort.selectionSort(list);
public class SelectionSort {
public static void selectionSort(double[] list) {
for (int i = 0; i < list.length - 1; i++) {
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i + 1; j < list.length; j++) {
if (currentMin > list[j]) {
currentMin = list[j];
currentMinIndex = j;
}
}
if (currentMinIndex != i) {
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
用于选择排序的维基百科条目可能是您正在寻找的.代码有解释过程的注释.实质上,Selection排序遍历数组并跟踪最小值.如果找到的新值小于之前找到的最小值,则交换这两个值.
/* a[0] to a[n-1] is the array to sort */
int i,j;
int iMin;
/* advance the position through the entire array */
/* (could do j < n-1 because single element is also min element) */
for (j = 0; j < n-1; j++) {
/* find the min element in the unsorted a[j .. n-1] */
/* assume the min is the first element */
iMin = j;
/* test against elements after j to find the smallest */
for ( i = j+1; i < n; i++) {
/* if this element is less, then it is the new minimum */
if (a[i] < a[iMin]) {
/* found new minimum; remember its index */
iMin = i;
}
}
/* iMin is the index of the minimum element. Swap it with the current position */
if ( iMin != j ) {
swap(a[j], a[iMin]);
}
}
Run Code Online (Sandbox Code Playgroud)