插入排序

4 篇文章 0 订阅
3 篇文章 0 订阅

title: 插入排序
date: 2019-07-19 10:17:55
summary: 插入排序(Insertion-Sort)
categories: 数据结构和算法
tags: [LeetCode,算法导论]

题目:

leetcode(912):
	给定一个整数数组 nums,将该数组升序排列。
		示例 1:   
			输入:[5,2,3,1]
			输出:[1,2,3,5]
		示例 2:
			输入:[5,1,1,2,0,0]
			输出:[0,0,1,1,2,5]
	提示:
		1 <= A.length <= 10000
		-50000 <= A[i] <= 50000
	来源:力扣(LeetCode)
	链接:https://leetcode-cn.com/problems/sort-an-array
	著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路:

	(稍后总结)

具体代码:

public int[] sortArray(int[] nums) {
    if(nums == null || nums.length == 1){
        return nums;
    }
    
    for(int currentInsetIndex = 1; currentInsetIndex < nums.length; currentInsetIndex++){
        int currentInset = nums[currentInsetIndex];
        
        int currentCompareIndex = currentInsetIndex - 1;
        
        while(currentCompareIndex >= 0 && nums[currentCompareIndex] > currentInset){
            nums[currentCompareIndex + 1] = nums[currentCompareIndex];
            currentCompareIndex--;
        }
        
        nums[currentCompareIndex + 1] = currentInset;
    }
    
    return nums;
}

运行结果:

执行结果:通过 显示详情
	执行用时 :
		407 ms, 在所有 Java 提交中击败了5.04%的用户
	内存消耗 :
		51.5 MB, 在所有 Java 提交中击败了100.00%的用户

结果分析:

由插入排序的特点:
	1.对于少量元素的排序,他是一个有效的算法
	2.原址排序
分析可得:
	1.由于每次插入都需要与前面已经排序好的进行比较,最坏情况下需要比较n次(n为每次插入已排序好的数组元素值),故对于10000这个数量的数组大小,插入排序表现得情况很差.
	2.由于插入排序进行原址排序,故内存消耗表现非常完美.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值