-1

我是 Java 初学者,目前正在阅读一本名为 Introduction to Java Programming 的书。在第 276 页上,有一个对数组进行选择排序的示例。我坐在这里试图解决几个小时,但我就是不明白。我知道这段代码是按升序对数组进行排序,但如果有人能更详细地解释代码的不同部分是什么,我将不胜感激做的正是。

    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;

                }
            }
        }
    }
4

2 回答 2

8

选择排序的Wikipedia 条目可能就是您要查找的内容。该代码有解释该过程的注释。本质上,选择排序遍历数组并跟踪最小值。如果找到的新值小于之前找到的最小值,则交换这两个值。

/* 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]);
    }
}
于 2013-01-04T20:04:55.040 回答
2

这是选择排序算法。它找到最小数字并将其放在顶部,如果找到较小的数字,则将其放在顶部,它会一直这样做,直到整个列表从最小到最大排序。阅读更多:http ://en.wikipedia.org/wiki/Selection_sort

于 2013-01-04T20:05:07.923 回答