选择排序
2014-09-19 18:07 微尘_无名 阅读(156) 评论(0) 编辑 收藏 举报选择排序的关键思想就是每次从后面未排序的部分选择最“小”值和未排序部分的第一个元素交换,当整个序列都有序的时候排序结束。简易代码实现及测试用例如下:
import java.util.logging.Handler; public class Selection { private static void exch(Comparable[] a, int i, int j) { Comparable tmp = a[i]; a[i] = a[j]; a[j] = tmp; } private static boolean less(Comparable a, Comparable b) { return (a.compareTo(b) < 0); } private static void show(Comparable[] a) { int N = a.length; for (int i = 0; i < N; i++) { System.out.print(a[i] + " "); } System.out.println(); } public static boolean isSorted(Comparable[] a) { int N = a.length; for (int i = 1; i < N; i++) { if (less(a[i], a[i - 1])) return false; } return true; } public static void sort(Comparable[] a) { int N = a.length; for (int i = 0; i < N; i++) { int min = i; for (int j = i + 1; j < N; j++) { if (less(a[j], a[min])) min = j; } exch(a, i, min); } } public static void main(String[] args) { String[] a = StdIn.readAllStrings(); Selection.sort(a); show(a); } }