java算法:插入排序

java算法:插入排序

如,对EXAMPLE 字母进行排序:
 E   X   A   M   P   L   E   开始
 E  [X]  A   M   P   L   E   E<X 不变
[A]  E   X   M   P   L   E   A < E:A插入到E前
 A   E  [M]  X   P   L   E   ...
 A   E   M  [P]  X   L   E  
 A   E  [L]  M   P   X   E  
 A   E  [E]  L   M   P   X 

Java代码 复制代码
  1. public class Insertion {   
  2.   
  3.     public static void main(String[] args) {   
  4.         int n = 20;   
  5.         MyItem [] a = new MyItem[n];   
  6.         for (int i = 0; i < n; i++) {   
  7.             a[i] = new MyItem();   
  8.             a[i].rand();   
  9.         }   
  10.            
  11.         for (int i = 0; i < n; i++) {   
  12.             System.out.print(a[i] + " ");   
  13.         }   
  14.            
  15.         insertion(a, 0, n);   
  16.         System.out.println("");   
  17.         print(a, n);   
  18.     }   
  19.        
  20.     private static void print(MyItem a [], int n){   
  21.         for (int i = 0; i < n; i++) {   
  22.             System.out.print(a[i] + " ");   
  23.         }   
  24.     }   
  25.        
  26.     public static void insertion(MyItem [] a, int l, int r){   
  27.         int i;   
  28.         for(i = r - 1; i >= l + 1; i--){   
  29.             compExch(a, i-1, i);   
  30.         }   
  31.         for (i = l + 2; i < r; i++){   
  32.             int j = i;   
  33.             MyItem v = a[i];   
  34.             while(less(v, a[j - 1])){   
  35.                 a[j] = a[j - 1];    
  36.                 j--;   
  37.             }   
  38.             a[j] = v;   
  39.         }   
  40.     }   
  41.        
  42.     public static boolean less(Item v, Item w){   
  43.         return v.less(w);   
  44.     }   
  45.        
  46.     public static void exch(Item [] a, int i, int j){   
  47.         Item t = a[i];   
  48.         a[i] = a[j];   
  49.         a[j] = t;   
  50.     }   
  51.        
  52.     public static void compExch(Item [] a, int i, int j){   
  53.         if(less(a[j],a[i])){   
  54.             exch(a, i, j);   
  55.         }   
  56.     }   
  57. }  

插入排序的运行时间主要依赖于输入文件中关键字的最初顺序。如,文件很大而且关键字已经排好(或者几乎排好),那么插入排序运算就很快了,而选择排序运行却很慢。

posted on 2012-11-01 10:03  吴一达  阅读(226)  评论(0编辑  收藏  举报

导航