插入排序

创建一个有序的数组,之后从从无序数组中进行一个个插入,变成有序数组。

代码实现:

 1     public class InsertSort {  
 2         InsertSort(int a[]){  
 3             int length = a.length;  
 4             for(int j = 1; j <= length - 1; j++){    //进行循环  
 5                 int i = j - 1;        
 6                 int temp = a[j];                    //要插入的数字  
 7                 while(a[i] > temp){                  //在已排好序的序列中寻找应放入的位置  
 8                     a[i + 1] = a[i];                //把较大的数前移  
 9                     i --;                           //继续比较下一个数  
10                     if(i < 0)  
11                         break;  
12                 }  
13                 a[i + 1] = temp;  
14             }  
15         }  
16         public static void main(String args[]){  
17             int a[] = {6,8,9,43,89,5,7,3,};  
18             InsertSort s = new InsertSort(a);  
19             for(int n:a)  
20                 System.out.println(n);  
21         }  
22     }  

 

posted @ 2016-07-13 17:05  清风雨下  阅读(188)  评论(0编辑  收藏  举报