java的插入算法学习
实现代码:
public class Insertion {
@SuppressWarnings({ "rawtypes", "unchecked" })
private static boolean less(Comparable v, Comparable m){
return v.compareTo(m) < 0;
}
@SuppressWarnings({ "unused", "rawtypes" })
private static void exch(Comparable [] a, int i, int j){
Comparable t = a[i];
a[i] = a[j];
a[j] = t;
}
@SuppressWarnings({ "unused", "rawtypes" })
private static void show(Comparable [] a){
System.out.println("排序之后:");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + " ");
}
}
@SuppressWarnings("rawtypes")
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;
}
@SuppressWarnings("rawtypes")
public static void sort(Comparable [] a){
int N = a.length;
for (int i = 1; i < N; i++) {
//将a[i]插入到a[-1],a[i-2],a[i-3]...之中
for (int j = i; j > 0 && less(a[j], a[j-1]); j--)
exch(a, j, j-1);
}
}
@SuppressWarnings("rawtypes")
public static void main(String[] args) {
//Comparable[] a = {49,38,65,97,76,13,27,49,78,34,12,64,1,8};
String [] a = {"s","o","r","t","e","x","a","m","p","l","e"};
System.out.println("排序之前:");
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
System.out.println();
sort(a);
assert isSorted(a);
show(a);
}
}
排序之前:
s o r t e x a m p l e
排序之后:
a e e l m o p r s t x
算法分析:
- 直接插入排序是稳定的排序;
- 文件初态不同时,直接插入排序所耗费的时间有很大差异。若文件初态为正序,则每个待插入的记录只需要比较一次就能够找到合适的位置插入,故算法的时间复杂 度为O(n),这时最好的情况。若初态为反序,则第i个待插入记录需要比较i+1次才能找到合适位置插入,故时间复杂度为O(n2),这是最坏的情况,直接插入排序的时间复杂度为0(n2);