Introduction to Algorithms-chapter 6 heap Sequencing

Source: Internet
Author: User

Order

This article mainly introduces the heap sorting algorithm (heapsort), the heap sort is like the merge sort rather than the insertion sort, the heap sort runs at O (NLGN); Like an insert sort rather than a merge sort, it is an in-place sort algorithm. At any time, only a constant number of elements in an array are stored outside the input array, so that the heap sort combines the advantages of inserting sort and merging sorting.
Heap sequencing also introduces an additional algorithm design technique that uses a data structure (the "heap" in this algorithm) to manage the information in the execution of the algorithm. Heap data structures are not only useful in heap sorting algorithms, but can also form an effective priority queue. A heap data structure is an array object that can be treated as a complete binary tree, where each node corresponds to the element that holds the node value in the array. Each layer of the tree is filled, except for the last layer (the last layer is filled from the Zuozi of a node).
The heap data structure is applied effectively in the maximum (minimum) priority queue, in this paper, the implementation of the heap sorting algorithm and the algorithm implementation of the maximal priority queue are given in detail in the case of the large top heap.

Heap Data structures

The heap data structure is an array abstraction, which can be seen as a complete binary tree, with each node in the tree corresponding to the element that holds the node value in the array. In addition to the top root node, all tree nodes have parent nodes, and in the same vein, all tree nodes have at least one son node in addition to the leaf nodes.

//求左儿子结点int Left(int i){    return2 * i;}//求右儿子结点int Right(int i){    return21;}//求父节点int Parent(int i){    return2;}

In the heap sorting algorithm, there are several key steps:
The maxheapify process, whose running time is O (Logn), is the key to keep the maximum heap properties;
Buildmaxheap the process, build a big top heap, construct a big top heap in the disordered primitive array;
Heapsort process, the large top heap from the last leaf node to start processing sorting, get a set of ascending sequence.

Implementation of heap sorting algorithm

(1) MaxHeap.h

#ifndef Max_heap_h#define MAX_HEAP_H/ * * Large top heap MAXHEAP data structure */#include <iostream>using namespace STD;classmaxheap{ Public: Maxheap (int*data,intsize); ~maxheap ();voidMaxheapsort ();voidDisplaylist (intSize) { for(inti =0; i < size; i++)cout<< M_datalist[i] <<"\ T";cout<< Endl; }Private:int*m_datalist;intM_heapsize;voidBuildmaxheap (int*data);voidMaxheapify (int*data,inti);intLeft (inti) {return 2I }intRight (inti) {return 2* i +1; }voidSwapint&a,int&AMP;B) {inttemp = A;        A = b;    b = temp; }};#endif

(2) MaxHeap.cpp

#include "MaxHeap.h"#include <iostream>usingnamespace Std;Maxheap::Maxheap(int * data, int size): M_datalist(data), m_heapsize(size) {}Maxheap::~Maxheap() {delete m_datalist;}void Maxheap:: buildmaxheap (int * data){for (int i = m_heapsize/2; I >=1; I--){Maxheapify ( Data, i);}}void Maxheap:: maxheapify (int * data, int i){int largest; int left = Left(i); int right = Right(i);if(Left <= m_heapsize && Data[left-1] > data[i-1])largest = left;Elselargest = i;if(Right <= m_heapsize && Data[right-1] > data[largest-1])largest = right;if(Largest! = i) {Swap ( Data[i-1], data[largest-1]);Maxheapify ( data, largest);}}void Maxheap:: Maxheapsort () {buildmaxheap (m_datalist);    int length = M_heapsize; for (int i = length; I >=1; I--){Swap (M_datalist[i-1], m_datalist[0]); M_heapsize--;Maxheapify (M_datalist,1); }}

(3) Main.cpp

#include "MaxHeap.h"#include <iostream>#include <cstdlib>#include <ctime>using namespace STD;Const intN =Ten;intMain () {//Declare an array to be sorted    int Array[N];//Set randomization seed to avoid generating the same random number each timeSrand (Time (0)); for(inti =0; i<n; i++) {Array[I] = rand ()%101;//array assignment uses random functions to generate random numbers between 1-100}//Call heap sort function to sort the arrayMaxheap *maxheap =NewMaxheap (Array+ i);cout<<"before sorting:"<< Endl;    Maxheap->displaylist (N); Maxheap->maxheapsort ();cout<< Endl <<"After sorting:"<< Endl;    Maxheap->displaylist (N); System"Pause");return 0;}

Test results:

Maximum priority queue

A priority queue is a data structure used to maintain a set of elements that consist of a collection element, each of which has a keyword key, which is divided into the maximum priority queue and the minimum priority queue.
This chapter focuses on the maximum priority queue based on the maximum heap implementation.
A maximum priority queue has the following key operations:
Insert (x): Inserts the keyword x into the collection and preserves the nature of the collection;
MaxiMum (): Returns the element of the largest keyword in the collection, and for the maximum priority queue, the team head element is the maximum keyword element;
Extractmax (): Removes and returns the element of the largest keyword in the queue collection;
Increasekey (x, K): Increases the value of the key at the position x of the element to K, and the value of K is not less than the initial value of the x position element;

Algorithm implementation:
(1) MaxPriQueue.h

#ifndef _maxpriqueue_h_#define _MAXPRIQUEUE_H_/** maximum heap implementation maximum priority queue data structure * /#include <iostream>using namespace STD;classmaxpriqueue{ Public: Maxpriqueue (int*data,intsize); ~maxpriqueue ();//Insert element X into the priority queue    voidInsertintx);//Remove and return the element with the largest keyword in the queue    intExtractmax ();//Add the value of the keyword of element x to K    voidIncreasekey (intXintk);voidMaxheapify (int*data,inti);intMaxiMum () {returnm_datalist[0]; }voidDisplaylist () { for(inti =0; i < m_queuesize; i++)cout<< M_datalist[i] <<"\ T";cout<< Endl; }Private:int*m_datalist;intM_queuesize;//Priority current length    //Seek the left son's knot.    intLeft (inti) {return 2I }//Seek the right son's knot.    intRight (inti) {return 2* i +1; }//Request parent Node    intParent (inti) {returnI2; }voidSwapint&a,int&AMP;B) {inttemp = A;        A = b;    b = temp; }voidBuildmaxheap (int*data);};#endif

(2) MaxPriQueue.cpp

#include "MaxPriQueue.h"#include <iostream>using namespace STD;//ConstructorsMaxpriqueue::maxpriqueue (int*data,intSize): m_datalist (data), m_queuesize (size) {//Build a large top pileBuildmaxheap (m_datalist);} Maxpriqueue::~maxpriqueue () {DeleteM_datalist;}voidMaxpriqueue::buildmaxheap (int*data) {//Bottom-up adjustment from the last root element     for(inti = m_queuesize/2; I >=1; i--) maxheapify (data, i);}intMaxpriqueue::extractmax () {if(M_queuesize <1)return-1;intmax = m_datalist[0]; m_datalist[0] = m_datalist[m_queuesize-1];    m_queuesize--; Maxheapify (M_datalist,1);returnMax;}voidMaxpriqueue::increasekey (intXintK) {if(K < m_datalist[x-1])return; m_datalist[x-1] = k;//Bottom-up adjustment large top pile     while(X >1&& m_datalist[parent (x)-1] < m_datalist[x-1]) {Swap (m_datalist[parent (x)-1], m_datalist[x-1]);    x = Parent (x); }}voidMaxpriqueue::insert (intx) {m_queuesize++; M_datalist[m_queuesize-1] = X1; Increasekey (m_queuesize, x);}voidMaxpriqueue::maxheapify (int*data,inti) {intlargest;intleft = left (i);intright = right (i);if(left <= m_queuesize && data[left-1] > Data[i-1]) largest = left;Elselargest = i;if(Right <= m_queuesize && data[right-1] > Data[largest-1]) largest = right;if(Largest! = i) {Swap (Data[i-1], Data[largest-1]);    Maxheapify (data, largest); }}

(3) Main.cpp

#include "MaxPriQueue.h"#include <iostream>#include <cstdlib>#include <ctime>using namespace STD;Const intN =Ten;intMain () {//Declare an array to be sorted    int Array[N];//Set randomization seed to avoid generating the same random number each timeSrand (Time (0)); for(inti =0; i<n; i++) {Array[I] = rand ()%101;//array assignment uses random functions to generate random numbers between 1-100}//Call heap sort function to sort the arrayMaxpriqueue *maxpriqueue =NewMaxpriqueue (Array+ i);cout<<"Big Top pile:"<< Endl; Maxpriqueue->displaylist ();cout<<"Heap top element"<< maxpriqueue->maximum () << Endl;cout<<"Delete Maximum element"<< Maxpriqueue->extractmax () << Endl;cout<<"The new Big Top heap:"<< Endl; Maxpriqueue->displaylist ();cout<<"Increase the team head element to."<< Endl; Maxpriqueue->increasekey (1, -);cout<<"The new Big Top heap:"<< Endl;    Maxpriqueue->displaylist (); System"Pause");return 0;}

Test results:

Exercise Analysis Solutions

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Introduction to Algorithms-chapter 6 heap Sequencing

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.