package foo; import java.util.Arrays; public class Main { public static void selectionSort(int[] a, int len) { int in, out, min; for (out=0;out<len-1;++out) { min = out; for (in=out+1;in<len;++in) { if(a[in]<a[min]) { min = in; } } swap(a, out, min); } } public static void swap(int[] a, int index1, int index2) { int temp = a[index1]; a[index1] = a[index2]; a[index2] = temp; } public static void main(String[] args) throws Exception { int[] a = new int[]{3,2,1,5,4}; selectionSort(a, a.length); System.out.println(Arrays.toString(a)); } }
选择排序的效率:O(N*N),比较N*N/2,交换<N; 选择排序与冒泡排序比较,比较次数没有明显改变,但交换次数明显减少了很多