----------------排序算法-之选择排序-------------

=======书瓖果========

定义:首先,找到数组中最小的那个元素,其次,将它和数组中的第一个元素交换位置(如果第一个元素就是最小元素那么它就和自己交换)。再次

结论:对于长度为N的数组,选择排序需要大约N2/2次比较和N次交换。

《算法基础》给出的伪码:

void selectionsort(int n, keytype s[]) {
    index i. j, smallest;
    for(i = 1; i <= n-1; i++) {
    smallest = i;
    for(j = i+1; j <= n; j++) {
        if(S[j] < S[smallest]) {
            smallest = j;
        }
           交换S[i] 和 S[smallest];
    }
}

《算法》实现:

/**
 * @author shuxiangguo
 * @time 2016/07/24
 * */
public class Selection {
	public static void sort(Comparable[] a) {
		//将a[]按升序排列
		int N = a.length;//数组长度
		for(int i = 0; i < N; i++) {
			//将a[i] 和 a[i+1..N]中最小的元素交换
			int min = i;//最小元素的索引
			for(int j = i+1; j < N; j++) {
				if(less(a[j], a[min]) {
					min = j;
				}
			}
			exch(a, i, min);
		}
	}

	private static boolean less(Comparable v, Comparable w) {
		return v.compareTo(w) < 0;
	}
	private static void exch(Comparable[] a, int i, int j) {
		Comparable t = a[i];
		a[i] = a[j];
		a[j] = t;
	}
	private static void show(Comparable[] a) {
		//在单行中打印数组
		for(int i = 0; i < a.length; i++) {
			StdOut.print(a[i] + " ");
		}
		StdOut.println();
	}
	public static boolean isSorted(Comparable[] a) {
		//测试数组是否有序
		for(int i = 1; i < a.length; i++) {
			if(less(a[i], a[i-1]))
			{
				return false;
			}
			return true;
		}
		public static void main(String[] args) {
			//从标准输入读取字符串,将它们排序输出
			String[] a = In.readStrings();
			sort(a);
			assert isSorted(a);
			show(a);
		}
	}
原文地址:https://www.cnblogs.com/shuxiangguo/p/5701942.html