选择排序需要大约N^2 / 2次比较和N次交换,其运行时间与输入无关且数据移动次数是最少的,具体实现代码如下:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Created by ZYQ on 2016/8/1.
*/
public class SelectionSort {
// 将数组a升序排列
public static void slSort(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); // 交换a[i]和数组a中的最小值
}
}
// 比较两个值的大小
private static boolean less(Comparable v, Comparable w) {
return v.compareTo(w) < 0;
}
// 交换两个元素的位置
private static void exch(Comparable[] a, int i, int j) {
Comparable temp = a[i];
a[i] = a[j];
a[j] = temp;
}
// 在单行中打印数组
private static void show(Comparable[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
System.out.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) throws IOException {
System.out.println("Enter the statements:");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String input = reader.readLine();
String[] item = input.split(" ");
slSort(item); // 对数组进行选择排序
show(item);
System.out.println("is sorted: " + isSorted(item));
}
}