排序算法之二直接插入排序

直接插入排序介绍

  基本思想:顺序的把待排序的数据元素按照其值的大小插入到已排好序的子集合的适当位置。子集合的数据元素个数从只有一个数据元素开始,逐次增大,当子集合大小最终和集合大小相同时,排序完毕。

直接插入排序过程

  首先第一个数已排好序,组成有序子集合,然后在依次在集合中取未排序数据元素和有序子集合中的数据元素进行比较,找到合适的位置并插入,直到有序子集合的大小最终和集合大小相同,排序即完成。

初始数据元素:31  12  7  10  15  13

初始排序:【31】  12  7  10  15  13

第一次排序:【12  31】  7  10  15  13

第二次排序:【7  12  31】  10  15  13

第三次排序:【7  10  12  31】  15  13

第四次排序:【7  10  12  15  31】  13

第五次排序:【7  10  12  13  15  31】

排序完成后的顺序:7  10  12  13  15  31

算法实现:

 

/**
     * 直接插入算法
     * @param array
     * @param length
     */
    public static void insertSort(int[] array, int length) {
        for(int i=1;i<array.length;i++){
            if(array[i]<array[i-1]){
                int temp=array[i];
                int j;
                for(j=i-1;j>=0&&array[j]>temp;j--){
                    array[j+1]=array[j];
                }
                array[j+1]=temp;
            }
            
        }
        
    }

测试代码:

public class SelectSort2 {
    public static void main(String[] args) {
        int[] array={12,32,21,3,74};
        System.out.printf("排序前:");
        
        //打印排序前数据元素
        for(int i=0;i<array.length;i++){
            System.out.printf("%d ",array[i]);
        }
        insertSort(array,array.length);//调用插入排序方法进行排序
        System.out.printf("排序后:");
        
        //打印排序后数据元素
        for(int i=0;i<array.length;i++){
            System.out.printf("%d ",array[i]);
        }
        
    }
    /**
     * 直接插入算法
     * @param array
     * @param length
     */
    private static void insertSort(int[] array, int length) {
        for(int i=1;i<array.length;i++){
            if(array[i]<array[i-1]){
                int temp=array[i];
                int j;
                for(j=i-1;j>=0&&array[j]>temp;j--){
                    array[j+1]=array[j];
                }
                array[j+1]=temp;
            }
            
        }
        
    }

结果:

排序前:12 32 21 3 74 排序后:3 12 21 32 74 

posted @ 2017-10-29 22:21  似水年华2017  阅读(113)  评论(0)    收藏  举报