java基础算法之插入排序算法

        插入排序是一种简单直观的排序算法,其工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。插入排序在实现上通常采用in-place排序(即只需用到O(1)的额外空间的排序),因而在从后向前扫描过程中,需要反复把已排序元素逐步向后挪位,为最新元素提供插入空间。

package com.example.datastructures.sort;

import java.util.Arrays;

/**
 * @author maoyouhua
 * @version jdk21
 *
 *        插入排序是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。
 *        插入排序在实现上通常采用in-place排序(即只需用到O(1)的额外空间的排序),
 *        因而在从后向前扫描过程中,需要反复把已排序元素逐步向后挪位,为最新元素提供插入空间。
 */
public class InsertSort {

    /**     思路:从后往前遍历,前面部分已经是有序的,被插入数小于当前数即可
     *
     * @param arr 待排序数组
     */
    private static void insertSort(int[] arr){
        for (int i = 1; i < arr.length; i++) {
            int insertValue = arr[i];
            int insertIndex = i-1;
            while (insertIndex >= 0 && insertValue < arr[insertIndex]){
                arr[insertIndex + 1] = arr[insertIndex];
                insertIndex--;
            }
            arr[insertIndex + 1] = insertValue;
            System.out.println("第"+ i +"轮输入");
            System.out.println(Arrays.toString(arr));
        }
    }

    /**
     *      排序效率测试
     *      花费时间是:681毫秒
     */
    private static void efficiencyTest(){
        int capacity = 80000;
        int[] arr = new int[capacity];
        for (int i = 0; i < capacity; i++) {
            arr[i] = (int)(Math.random()  * 100 * capacity);
        }
        long start = System.currentTimeMillis();
        insertSort(arr);
        long end = System.currentTimeMillis();
        System.out.println("花费时间是:" + (end - start) + "毫秒");
    }

    /**
     * 第1轮输入
     * [3, 17, 15, 14, 1, 9]
     * 第2轮输入
     * [3, 15, 17, 14, 1, 9]
     * 第3轮输入
     * [3, 14, 15, 17, 1, 9]
     * 第4轮输入
     * [1, 3, 14, 15, 17, 9]
     * 第5轮输入
     * [1, 3, 9, 14, 15, 17]
     */
    public static void main(String[] args) {
        int[] arr = {17, 3, 15, 14, 1, 9};
        insertSort(arr);
        efficiencyTest();
    }
}

  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值