排序算法之直接插入排序的思想以及Java实现

1,基本思想
假设待排序的数据是数组A[1….n]。初始时,A[1]自成1个有序区,无序区为A[2….n]。在排序的过程中,依次将A[i] (i=2,3,….,n)从后往前插入到前面已排好序的子数组A[1,…,i-1]中的适当位置,当所有的A[i] 插入完毕,数组A中就包含了已排好序的输出序列。

2,算法的实现(Java)

package Algorithm;

public class InsertSort {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] a={11,10,55,78,100,111,45,56,79,90,345,1000};//创建一个数组a
        System.out.println("排序之前:");
        InsertSort.output(a);
        System.out.println();
        InsertSort.Sort(a);
        System.out.println("排序之后:");
        InsertSort.output(a);
    }
    //插入排序
    public static void Sort(int[] arr){
        for(int i=1;i<arr.length;i++){
            int tempdata = arr[i];
            int j;
            for(j=i-1;j>=0;j--){
                 if(arr[j]>tempdata){
                     arr[j+1] = arr[j];
                 }else{
                     break;
                 }
            }
            arr[j+1] = tempdata;
        }
    }
    //输出打印
    public static void output(int[] arr){
        for(int i=0;i<arr.length;i++){
            System.out.print(arr[i]+",");
        }
    }
}

得到的结果如下所示:
这里写图片描述

3,性能分析
空间复杂度 O(1)
时间复杂度O(n^2)

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

攻城狮joe

码字不易,且看且珍惜

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值