插入排序

插入排序是通过比较和插入来实现排序的;

排序思想:

a)首先对数组的前两个数据进行从小到大的排序;

b)接着将第三个数据与排好顺序的两个数据比较,将第三个数据插入合适的位置;

c)然后,将第4个数据插入到已经排好顺序的前3个数据中;

d)不断重复上述过程

 1 package insert_sort;
 2 
 3 public class InsertSort {
 4     /*
 5      * 插入排序
 6      * */
 7     public static void main(String[] args) {
 8         int[] a = {0,5,2,6,9,3,4,8,1};
 9         int i,j,t,h;
10         for(i=1;i<a.length;i++){
11             t = a[i];        
12             j = i-1;
13             while(j>=0 && t<a[j]){    //此处的t不能 用a[i]代替,因为i=j+1
14                 a[j+1] = a[j];
15                 j--;
16             }
17             a[j+1] = t;
18         }
19         
20         for(int x=0;x<a.length;x++)
21             System.out.print(a[x]+ "、");    
22     }
23 }

 

posted @ 2017-08-16 15:48  XuGuobao  阅读(175)  评论(0编辑  收藏  举报