Java八大算法:插入排序

基本原理

插入排序(英语:Insertion Sort)是一种简单直观的排序算法。它的工作原理是通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。插入排序在实现上,在从后向前扫描过程中,需要反复把已排序元素逐步向后挪位,为最新元素提供插入空间。

动态图

代码(这个地方用的是前后交换的方式)

package com.qcby;

import java.util.Arrays;

public class Shu {


	public static void main(String[] args) {
        int[] arr = new int[] {6,5,3 ,1,8,7,2,4};
        Sort(arr);
    }
    public static void Sort(int[] arr) {
        for (int i = 1; i < arr.length; i++) {
            //将当前数据插入到已经有序的数字当中(这里需要倒着往前找)
            for ( int j = i-1; j >= 0; j--) {
                //前后位置进行交换
                if (arr[j] > arr[j+1]) {
                    int temp = arr[j];
                    arr[j] = arr[j+1];
                    arr[j+1] = temp;
                }else {
                    break;
                }
            }
            System.out.println(Arrays.toString(arr));
        }
    }
}

输出结果如下:

[5, 6, 3, 1, 8, 7, 2, 4]
[3, 5, 6, 1, 8, 7, 2, 4]
[1, 3, 5, 6, 8, 7, 2, 4]
[1, 3, 5, 6, 8, 7, 2, 4]
[1, 3, 5, 6, 7, 8, 2, 4]
[1, 2, 3, 5, 6, 7, 8, 4]
[1, 2, 3, 4, 5, 6, 7, 8]

代码(移位方式)

package com.qcby;

import java.util.Arrays;

public class Shu {


	public static void main(String[] args) {
        int[] arr = {-1,100,4,23,2,45,67,89,-3,56};
        System.out.print("排序前:");
        System.out.println(Arrays.toString(arr));
        insertSort(arr);
    }

    //直接插入排序(移位方式)
    public static void insertSort(int[] arr){
        for(int i=1;i<arr.length;i++){
           int insertVal = arr[i];
           int insertIndex = i;
           while (insertIndex>0 && insertVal<arr[insertIndex-1]){
               arr[insertIndex]=arr[insertIndex-1];
               insertIndex--;
           }
           arr[insertIndex] = insertVal;
           //输出每趟的结果
           System.out.print("第" + i + "轮:");
           System.out.println(Arrays.toString(arr));
        }
        //排序完成后输出最终的结果
        System.out.println("==================================================");
        System.out.println(Arrays.toString(arr));
    }
}

输出结果如下:

排序前:[-1, 100, 4, 23, 2, 45, 67, 89, -3, 56]
第1轮:[-1, 100, 4, 23, 2, 45, 67, 89, -3, 56]
第2轮:[-1, 4, 100, 23, 2, 45, 67, 89, -3, 56]
第3轮:[-1, 4, 23, 100, 2, 45, 67, 89, -3, 56]
第4轮:[-1, 2, 4, 23, 100, 45, 67, 89, -3, 56]
第5轮:[-1, 2, 4, 23, 45, 100, 67, 89, -3, 56]
第6轮:[-1, 2, 4, 23, 45, 67, 100, 89, -3, 56]
第7轮:[-1, 2, 4, 23, 45, 67, 89, 100, -3, 56]
第8轮:[-3, -1, 2, 4, 23, 45, 67, 89, 100, 56]
第9轮:[-3, -1, 2, 4, 23, 45, 56, 67, 89, 100]
==================================================
[-3, -1, 2, 4, 23, 45, 56, 67, 89, 100]

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值