JAVA 插入排序(直接插入)


  1. public class Test {  
  2.   
  3.      static void Insert(int a[])  
  4.         {  
  5.          int j;  
  6.          for (int i = 1; i < a.length; i++) {//把第一个数作为基点,后面的数都和它比较   
  7.             int temp=a[i];  
  8.             j=i;  
  9.             while (j>0&&(a[j-1]>=temp)) {       
  10.                 a[j]=a[j-1];  
  11.                 --j;            
  12.             }  
  13.             a[j]=temp;  
  14.             System.out.print("\n第"+i+"次的结果是:");  
  15.             for (int k = 0; k < a.length; k++) {  
  16.                 System.out.print(a[k]+" ");  
  17.             }  
  18.             System.out.println();  
  19.          }  
  20.         }  
  21.        
  22.     public static void main(String[] args) {  
  23.         // TODO Auto-generated method stub   
  24.      int Arra[] =new int[]{2,4,6,1,3};   
  25.       Insert(Arra);  
  26.     for (int i = 0; i < Arra.length; i++) {  
  27.         System.err.print(Arra[i]+" ");  
  28.     }  
  29.     }  
  30.    
  31. }     
 

相关内容