选择排序步骤:
1)第一轮逐一扫描所有数字,并取出最小那个放在第一位;
2)第二轮扫描剩下的数字,并取出第二小的那个数字放在第二位;
3)以此循环反复,直到所有数字都已经排序。
因为每次都是选择剩下数字中最小(大)那个,所以叫做选择排序。
选择排序大约花费 N2 次比较,和 N 次交换。
Selection.java
1 import java.util.ArrayList; 2 import java.util.Collections; 3 4 /** 5 * Selection sort uses ~(N^2)/2 compares and N exchanges to sort. 6 * @param <E> Comparable types 7 */ 8 public class Selection<E extends Comparable<E>> { 9 public void sort(ArrayList<E> a) { 10 if (a == null || a.isEmpty()) { 11 throw new IllegalArgumentException("The list is null or empty."); 12 } 13 14 final int N = a.size(); 15 if (N == 1) { 16 return; 17 } 18 19 for (int i = 0; i < N; i++) { 20 int mini = i; 21 for (int j = i+1; j < N; j++) { 22 if (a.get(j).compareTo(a.get(mini)) < 0) { // if a[j] < a[mini] 23 mini = j; 24 } 25 } 26 Collections.swap(a, i, mini); 27 } 28 } 29 }
其中关键代码是上面的19~27行。
测试代码:
Example.java
1 import java.util.ArrayList; 2 import java.util.Scanner; 3 4 public class Example<E extends Comparable<E>> { 5 6 public void sort(ArrayList<E> a) { 7 Selection<E> s = new Selection<>(); 8 s.sort(a); 9 } 10 11 public void show(ArrayList<E> a) { 12 if (a == null) { 13 throw new IllegalArgumentException("The list is null."); 14 } 15 16 for (E v : a) { 17 System.out.print(v + " "); 18 } 19 System.out.println(); 20 } 21 22 public boolean isSorted(ArrayList<E> a) { 23 if (a == null || a.isEmpty()) { 24 throw new IllegalArgumentException("The list is null or empty."); 25 } 26 27 for (int i = 1; i < a.size(); i++) { 28 if (a.get(i).compareTo(a.get(i-1)) < 0) { 29 return false; 30 } 31 } 32 return true; 33 } 34 35 public static void main(String[] args) { 36 ArrayList<String> a = new ArrayList<>(); 37 Scanner input = new Scanner(System.in); 38 Example<String> ex1 = new Example<>(); 39 40 while (input.hasNext()) { 41 a.add(input.next()); 42 } 43 44 ex1.sort(a); 45 assert ex1.isSorted(a); 46 ex1.show(a); 47 } 48 }
输入示例:
输出示例: