插入排序
-自然语言描述:
有一个已经有序的数据序列,要求在这个已经排好的数据序列中插入一个数,但要求插入后此数据序列仍然有序。
-Java语言描述:
public static void sort(Comparable[] a){
int N = a.length;
for (int i = 1; i < N; i++){
for (int j = i; j > 0&&(a[j] < a[j -1]); j--){
Comparable temp = a[j];
a[j] = a[j -1];
a[j -1] = temp;
}
}
}
-验证代码:
public class Insertion {
public static void sort(Comparable[] a){
//升序
int N = a.length;
for(int i = 1; i < N; i++){
for (int j = i; j >0&&less(a[j],a[j -1]) ; j-- ) {
exch(a, j, j -1);
}
}
}
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++)
System.out.print(a[i] + " ");
System.out.println();
}
public static boolean isSorted(Comparable[] a){
int length = a.length;
for (int i = 1;i < 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);
}
}