十五、插入排序算法(两种方式)

一、插入排序法思想

插入排序(Insertion Sorting)的基本思想是:把 n 个待排序的元素看成为一个有序表和一个无序表,开始时有 序表中只包含一个元素,无序表中包含有 n-1 个元素,排序过程中每次从无序表中取出第一个元素,把它的排 序码依次与有序表元素的排序码进行比较,将它插入到有序表中的适当位置,使之成为新的有序表。

二、插入排序思路图

在这里插入图片描述

三、插入排序算法第一种解法

package cn.zzw.algorithm.sort1;

import java.util.Arrays;

public class InsertSort {

    public static void main(String[] args) {
        int[] array={4,1,9,6,7,3,5};
        InsertSort(array);
    }

    public static void InsertSort(int array[])
    {
        for(int i=1;i<array.length;i++)
        {
            int InsertValue=array[i];
            int InsertIndex=i-1;
            while(InsertIndex>=0 && InsertValue<array[InsertIndex])
            {
                //元素后移
                array[InsertIndex+1]=array[InsertIndex];
                InsertIndex--;
            }

            //退出循环时,说明插入的位置找到,为InsertIndex+1
            array[InsertIndex+1]=InsertValue;
            System.out.println("第"+(i)+"趟排序结果为:"+Arrays.toString(array));
        }
        System.out.println("最终的排序结果为:"+ Arrays.toString(array));
    }
}

四、插入排序算法第二种解法

package cn.zzw.algorithm.test;

import java.util.Arrays;

public class InsertTest {
    public static void main(String[] args) {
        int[] a={4,3,2,4,10,12,1,5,6};
        for(int i=1;i<a.length;i++)
        {
            for(int j=i;j>0;j--)
            {
                if(a[j-1]>a[j])
                {
                    int temp=a[j-1];
                    a[j-1]=a[j];
                    a[j]=temp;
                }
                else
                {
                    break;
                }
            }
        }

        System.out.println(Arrays.toString(a));
    }

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值