选择排序
选择最小的一个元素放在第一个位置上,第二小的元素放在第二个位置,以此类推,直到待排序序列排序完成。
排序过程
待排序序列: 4, 6, 3, 1, 8, 9, 3
i = 0; min = 3 : 1, 6, 3, 4, 8, 9, 3
i = 1; min = 2 : 1, 3, 6, 4, 8, 9, 3
i = 2; min = 6 : 1, 3, 3, 4, 8, 9, 6
i = 3; min = 3 : 1, 3, 3, 4, 8, 9, 6
i = 4; min = 6 : 1, 3, 3, 4, 6, 9, 8
i = 5; min = 6 : 1, 3, 3, 4, 6, 8, 9
i = 6; min = 6 : 1, 3, 3, 4, 6, 8, 9
伪代码
select_sort(A)
for i = 0 to A.length
int min = i;
for j = i+1 to A.length
if (a[min] > a[j]) min = j;
temp = a[min];
a[min] = a[i];
a[i] = temp;
Java 实现
/**
* 选择排序算法
*/
public class SelectionSort {
//从小到大排序
public static <T extends Comparable<T>> void selectionSort(T[] a) {
for (int i = 0; i < a.length; i++) {
int min = i;
for (int j = i+1; j < a.length; j++) {
if (a[min].compareTo(a[j]) > 0) {
min = j;
}
}
exchange(a, i, min);
}
}
public static <T extends Comparable<T>> void exchange(T[] a, int source, int destination) {
T temp = a[source];
a[source] = a[destination];
a[destination] = temp;
}
public static void main(String[] args) {
Integer[] a = {4,6,3,1,8,9,3};
SelectionSort.selectionSort(a);
for (Integer item : a)
System.out.print(item + ",");
}
}