在计算机科学中,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 =