Algorithm 4_Heap_Sort

本文介绍了一种基于二叉堆数据结构的高效排序算法——堆排序。首先定义了二叉堆的概念,并给出了实现堆的关键操作,如调整最大堆(MaxHeapify)等。接着详细解释了如何从数组构建最大堆并进行排序的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 First of all,the binary heap is an array that can be viewd as a nearly completely binary tree.Each node of the tree corresponds to an element of the arrau that stores the value in the node.

   We can simply implement the heap as following codes:

    class Heap
    
{
        
private Int32 size;

        
public Int32 Size
        
{
            
get return size; }
            
set { size = value; }
        }


        
public Int32 Parent(Int32 index)
        
{
            
return (index-1)/2;
        }


        
public Int32 Left(Int32 index)
        
{
            
return index * 2 + 1;
        }


        
public Int32 Right(Int32 index)
        
{
            
return index * 2 + 2;
        }

    }
 

One important function in this algorithm is MaxHeapify().Its input are an array A and an index I into the array.When this is called,it is assumed that the binary tree rooted at Left(i) and Right(i) are max heaps,but the A[i] may be smaller than its children,this violating the max heaps.This function is to let the value at A[i] float down in the max heao so that the subtree rooted at index I becomes a man heap.

  Let’s show you the code.

        private static void MaxHeapify(Int32[] arr, Int32 index)
        
{
            Int32 left 
= heap.Left(index);
            Int32 right 
= heap.Right(index);
            Int32 largest;

            
if (left < heap.Size && arr[left] > arr[index])
                largest 
= left;
            
else
                largest 
= index;
            
if (right < heap.Size && arr[right] > arr[largest])
                largest 
= right;
            
if (largest != index)
            
{
                Swap(arr, index, largest);
                MaxHeapify(arr, largest);
            }

        }

But before this function ,we need build a max heap from an array.

 
        //create a max heap from an array
        private static void BuildMaxHeap(Int32[] arr)
        
{
            heap.Size 
= arr.Length;
            
for (Int32 index = (arr.Length - 1/ 2; index >= 0; index--)
            
{
                MaxHeapify(arr, index);
            }

        }

 

So, we can sort write the algorithm simply.

        public static void Sort(Int32[] arr)
        {
            BuildMaxHeap(arr);
            for (Int32 index = arr.Length - 1; index > 0; index--)
            {
                Swap(arr, 0, index);
                heap.Size--;
                MaxHeapify(arr, 0);
            }
        }

 Heapsort’s running time is O(nlgn).
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值