【C#】程序员必须要掌握的算法(二)——堆排序

在计算机科学中,Heapsort(由J.W.J. Williams于1964年发明)是一种基于比较的排序算法。可以将Heapsort视为一种改进的选择排序:类似于该算法,它将输入分为已排序和未排序区域,并通过提取最大元素并将其移至已排序区域来交互式地缩小未排序区域。改进包括使用堆数据结构,而不是使用线性时间搜索来找到最大值。尽管在大多数机器实践中的速度比快速排序稍慢,但它的最坏,最好,平均时间复杂度均为O(nlogn)。Heapsort是一种原地算法,但不是稳定的排序。

堆排序动态演示

 

科普:什么是原地算法?

In computer science, an in-place algorithm is an algorithm which transforms input using no auxiliary data structure. However a small amount of extra storage space is allowed for auxiliary variables. The input is usually overwritten by the output as the algorithm executes. In-place algorithm updates input sequence only through replacement or swapping of elements. An algorithm which is not in-place is sometimes called not-in-place or out-of-place.

——In-place algorithm - Wikipedia

 

简单通俗地讲就是:原地算法不需要额外的资源或者依赖少数的额外资源,仅依靠输出来覆盖输入的一种算法操作,有效节省内存空间。

举个例子:假设我们有n个元素的数组,此时需要我们将数组逆转。

第一反应肯定会创建一个空数组来进行逆向存储:

/// <summary>
/// 数组元素逆转
/// </summary>
/// <param name="arr">原始数组</param>
/// <returns>排序后数组</returns>
private static int[] ReverseArray(int[] arr)
{
    int n =
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值