Algorithmic Heights第4题:Insertion Sort

Computing the number of swaps in insertion sort

Insertion sort is a simple sorting algorithm that builds the final sorted array one item at a time. It is much less efficient on large lists than more advanced algorithms such as “Quick Sort”“Heap Sort”, or “Merge Sort”. However, insertion sort provides several advantages: simple implementation, efficient for (quite) small data sets,  extra space.

When humans manually sort something (for example, a deck of playing cards), most use a method that is similar to insertion sort.

Source: Wikipedia

Although it is one of the elementary sorting algorithms with  worst-case time, insertion sort is the algorithm of choice either when the data is nearly sorted (because it is adaptive) or when the problem size is small (because it has low overhead).

For these reasons, and because it is also stable, insertion sort is often used as the recursive base case (when the problem size is small) for higher overhead divide-and-conquer sorting algorithms, such as “Merge Sort” or “Quick Sort”.

Visualization by David R. Martin: http://www.sorting-algorithms.com/insertion-sort

插入排序是一种简单的排序算法,可以一次构建一个最终的排序数组。与诸如“快速排序”“堆排序”“合并排序”之类的更高级算法相比,它在大型列表上的效率要低得多。但是,插入排序具有以下优点:实现简单,对(非常)小的数据集有效,  多余的空间。

当人们手动对某些东西(例如一副扑克牌)进行排序时,大多数人会使用类似于插入排序的方法。

资料来源:维基百科

尽管它是具有以下特征的基本排序算法之一  在最坏的情况下,插入排序是在数据接近排序(因为它是自适应的)或问题大小较小(因为它的开销很低)时选择的算法。

由于这些原因,并且由于它也是稳定的,因此通常将插入排序用作递归基本案例(问题大小较小时),以用于开销较大的分治式排序算法,例如“合并排序”“快速排序” ”

David R. Martin的可视化: http://www.sorting-algorithms.com/insertion-sort

 

Problem

Insertion sort is a simple algorithm with quadratic running time that builds the final sorted array one item at a time.

插入排序是一种具有二次运行时间的简单算法,可一次构建一个最终排序的数组。

Given: A positive integer  and an array  of integers.

Return: The number of swaps performed by insertion sort algorithm on .

给定:正整数 和一个数组  整数

返回值:插入排序算法对进行的交换次数

Sample Dataset

6
6 10 4 5 1 2

Sample Output

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值