1 基本思想
在未排序序列中找到最小元素,存放到未排序序列的起始位置。在所有的完全依靠交换去移动元素的排序方法中,选择排序属于非常好的一种算法,需要对比len-n-1次,但是只交换1次或者0次。
2 算法描述
①. 从待排序列中,找到最小的元素;
②. 如果最小元素不是待排序列的第一个,将其和第一个元素互换;
③. 从余下的 N – 1 个元素中,找出最小的元素,重复①、②步,直到排序结束。
3、代码实现:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
public class ChoiceSort { public static void main(String[] args) { int[] array = new int[]{10, 1, 9, 2, 8, 3, 7, 4, 6, 5}; choiceSort(array); } /** * 实例: * 10, 1, 9, 2, 8, 3, 7, 4, 6, 5 * 1, 10, 9, 2, 8, 3, 7, 4, 6, 5 * 1, 2, 9, 10, 8, 3, 7, 4, 6, 5 * 1, 2, 3, 10, 8, 9, 7, 4, 6, 5 * @param array */ public static void choiceSort(int[] array) { int len = array.length; for (int i=0; i<len-1; i++) { int minIndex = i; for (int j=i; j<len-1; j++) { // 将最小元素下标赋给minIndex if (array[minIndex] > array[j+1]) { minIndex = j+1; } } // 最小值不是未排序序列的第一个元素,则与其交换 if (minIndex != i) { SortUtil.swap(array, minIndex, i); } System.out.println(Arrays.toString(array)); } } }