Skip to content

Instantly share code, notes, and snippets.

@completejavascript
Created September 11, 2018 19:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save completejavascript/c6e40ed49a811e7fcd7e7607df433e9a to your computer and use it in GitHub Desktop.
Save completejavascript/c6e40ed49a811e7fcd7e7607df433e9a to your computer and use it in GitHub Desktop.
// Sắp xếp lại cây, sao cho phần tử cha luôn lớn hơn phần tử con của nó
void Heapify(int *a, int N, int i)
{
int Left = 2*i + 1, Right = 2*i + 2, Largest;
if(Left < N && a[Left] > a[i]) Largest = Left;
else Largest = i;
if(Right < N && a[Right] > a[Largest]) Largest = Right;
if(Largest != i)
{
swap(a[i], a[Largest]);
Heapify(a, N, Largest);
}
}
// Xây dựng mô hình cây nhị phân sao cho phần tử cha luôn lớn hơn phần tử con
void BuildHeap(int *a, int N)
{
for(int i = N/2-1; i >= 0; i--)
Heapify(a, N, i);
}
// Hàm chính
void Heap(int *a, int N)
{
BuildHeap(a, N);
for(int i = N - 1; i >= 0; i--)
{
// cho phần tử lớn nhất xuống dưới cùng,
// sau đó, cập nhật lại cây
swap(a[i], a[0]);
Heapify(a, i, 0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment