# 算法系列（三）插入排序的两种改进：规避边界检测和取消交换（Java实现）

public class Exer24 {

public static void sort(Comparable[] a){
int N = a.length;
for (int i = N-1; i > 0; i--) {
if(less(a[i],a[i-1]))
exch(a,i,i-1);
}
for (int i = 2; 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){  //比较v是否小于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;
}
public 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 class Exer25 {

public static void sort(Comparable[] a){
int N = a.length;
for (int i = 2; i < N; i++) {
Comparable t = a[i];
int j = i;
for (; j > 0 && less(t, a[j-1]); j--) {
a[j] = a[j-1]; //大的右移
}
a[j] = t;
}
}
private static boolean less(Comparable v, Comparable w){  //比较v是否小于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;
}
public 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;
}
}