(2)直接插入排序

来源:互联网 发布:在淘宝网怎么投诉卖家 编辑:程序博客网 时间:2024/06/05 00:45

基本思想:对于给定的一组记录,假设第一个记录自成一个有序序列,其余记录为无序序列。接着从第二个记录开始,按照记录的大小以此将当前处理的记录插入到其之前的有序序列中,直到最后一个记录插入到有序序列中为止。


例子:  45 56 67 15  35

第一步插入45:  [45] 56 67 15 35

第二步插入56      [45 56] 67 15 35

第三步插入67      [45 56 67] 15 35

第四步插入15      [15 45 56 67] 35

第五步插入35      [15 35 45 56 67]

public class TestSort{    public static void insertSort(int[] a){        if(a!=null){                for(int i=1;i<a.lenght;i++){                    int temp = a[i];                    j=i;                    if(a[j-1]>temp){                        for(j>=1&&a[j-1]>temp){                            a[j]=a[j-1];                            j--;                        }                    }                    a[j]=temp;                }            }    }    public static void main(String[] args){        int[] array={3,5,1,6,7};        insertSort(array);        for(int i=0;i<array.lenght;i++){            System.out.println(array[i]+" ");        }    }}