1、概述:
每一趟從待排序的數據元素中選出最小(或最大)的一個元素,順序放在已排好序的數列的最後,直到全部待排序的數據元素排完。
2、圖解:
3、java代碼:
package SelectionSort;
public class SelectionSort {
//排序方法
public static void sort(Comparable[] a) {
int N = a.length;//獲取數組長度
for (int i = 0; i < N; i++) {
int min = i;
//以下for循環找出最小元素下標
for (int j = i + 1; j < N; j++) {
if(less(a[j], a[min])) min = j;
}
//把最小元素移動到放在已排好序的數列的最後
exch(a, i, min);
}
}
public static boolean less(Comparable c1, Comparable c2) {
return c1.compareTo(c2) < 0;
}
public static void exch(Comparable[] c, int i, int j) {
Comparable tmp = c[i];
c[i] = c[j];
c[j] = tmp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Integer[] a = {12,23,9,24,15,3,18};
System.out.println("未排序數據:");
for(Integer t : a)
System.out.println(t);
sort(a);
System.out.println("已排序數據:");
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
}