Feel yourselfAlgorithmNot powerful... not familiar with basic concepts and basic operations
Let's go through the introduction to the entire algorithm... write most of the commonly used things by yourself.
It is really hard to do...
Get a common heap first
Heap can be used for heap sorting, priority queue, and so on.
Using System;
Using System. Collections. Generic;
Using System. LINQ;
Using System. text;
Using System. runtime. interopservices;
Namespace Introducetoalgorithm
{
Public Class Maxheap
{
/// <Summary>
/// Check the node is obey max_heap_property or not
/// </Summary>
/// <Param name = "A"> An int array represent a heap </Param>
/// <Param name = "I"> The node Index </Param>
/// <Param name = "alength"> The arry length, (some time, we will reduce the length of array) </Param>
Public Void Maxheapify ( Int [], Int I, Int Alength = - 1 )
{
Int Length = Alength <= - 1 ? A. Length: alength;
VaR L = Left (I );
VaR R = Right (I );
Int Largest = I;
If (L < Length && A [l] > A [I])
{
Largest = L;
}
If (R < Length && A [R] > A [Largest])
{
Largest = R;
}
If (Largest ! = I)
{
Exchange (A, I, largest );
Maxheapify (A, largest, alength );
}
// Maxheapify (A, L );
// Maxheapify (A, I );
}
Public Int Left ( Int Index)
{
Return (Index + 1 ) * 2 - 1 ;
}
Public Int Right ( Int Index)
{
Return (Index + 1 ) * 2 ;
}
Public Void Exchange ( Int [], Int I, Int I2)
{
Int Val = A [I];
A [I] = A [I2];
A [I2] = Val;
}
/// <Summary>
/// Build a max-heap, all element obey max-heap-Property
/// Wo only need check element which index less than a. Length/2-1
/// </Summary>
/// <Param name = "A"> </param>
Public Void Build_max_heap ( Int [])
{
For ( Int I = (A. Length / 2 - 1 ); I > = 0 ; I -- )
{
Maxheapify (A, I );
}
}
Public Void Heapsort ( Int [])
{
Int Length = A. length;
Build_max_heap ();
For ( Int I = A. Length - 1 ; I > = 1 ; I -- )
{
Exchange (, 0 , I );
Maxheapify (, 0 , -- Length );
}
}
}
}
PS: falseCodeSometimes it is very depressing. For example, the subscript of the C # array starts to be 0. In pseudo code, it is generally a mess of converting the values of 1...