package edu.cumt.jnotnull; public class SortArray { public static <T extends Comparable<? super T>> void selectionSort(T[] a, int n) { for (int index = 0; index < n - 1; index++) { int indexOfNextSmallest = getIndexOfSmallest(a, index, n - 1); swap(a, index, indexOfNextSmallest); } } public static <T extends Comparable<? super T>> void selectionSort(T[] a, int first, int last) { if (first <= last) { int indexOfNextSmallest = getIndexOfSmallest(a, first, last); swap(a, first, indexOfNextSmallest); selectionSort(a, first + 1, last); } } private static <T extends Comparable<? super T>> int getIndexOfSmallest( T[] a, int first, int last) { T min = a[first]; int indexOfMin = first; for (int index = first + 1; index < last; index++) { if (a[index].compareTo(min) < 0) { min = a[index]; indexOfMin = index; } } return indexOfMin; } private static void swap(Object[] a, int i, int j) { Object temp = a[i]; a[i] = a[j]; a[j] = temp; } }
迭代方法的算法效率
selectionSort执行了n-1次,所以各调用indexofsmallest和swap各n-1次.
在对indexofsmallest的调用中,last是n-1 first是n-2.每一次调用indexofsmallest,琪循环都执行了last-first次.因此这个循环共执行了(n-1)+(n-2)+...+1 也就是n(n-1)/2 .同时由于循环中的操作是O(1),所以选择排序效率是O(n^2).
同时注意,这里讨论与数组中元素的性质无关,可以是有序的 也可以是无序的.但是都是O(n^2).