1.binary Heap Implementation
BinaryHeap.h
#ifndef binaryheap_h#define binaryheap_hclass binaryheap{public : binaryheap (int N); BOOL IsEmpty (); void Exchange (int i,int j); void Insert (int key); int Delmax (); int Getmax (); Virtual ~binaryheap (); Protected: private: int N; int * DATA; void swim (int key); void sink (int key);}; #endif//Binaryheap_h
BinaryHeap.cpp
#include "BinaryHeap.h" #include <stdlib.h>binaryheap::binaryheap (int N) {this->n = 0; This->data = (int *) malloc (sizeof (int) * (n+1));} Binaryheap::~binaryheap () {}bool binaryheap::isempty () {return N = = 0;} void Binaryheap::exchange (int i,int j) {int temp = this->data[i]; This->data[i] = this->data[j]; THIS->DATA[J] = temp;} void Binaryheap::swim (int key) {while (Key > 1 && DATA[KEY/2] < Data[key]) {Exchange (Key/2,key) ; key = KEY/2; }}void binaryheap::insert (int key) {n++; Data[n] = key; Swim (N);} void Binaryheap::sink (int key) {while (key*2 <= N) {int j = key*2; if (J < N && Data[j] < data[j+1]) J + +; if (Data[key] >= data[j]) break; else {Exchange (KEY,J); key = J; }}}int binaryheap::d Elmax () {int max = data[1]; Exchange (1,N-1); n--; Sink (1); return Max;} int Binaryheap::getmax () {return data[1];}
Main.c
#include <iostream> #include "BinaryHeap.h" using namespace Std;int Main () { binaryheap * bp = new Binaryheap (10) ; Bp->insert (3); Bp->insert (2); Bp->insert (1); Bp->insert (5); Bp->insert (8); Bp->insert (7); cout << Bp->getmax () << "\ n"; Bp->delmax (); cout << Bp->getmax () << "\ n"; char c; CIN >> C; return 0;}
Analysis of the complexity of each operation time:
2. Heap Sequencing
Main steps for heap sequencing:
(1) Building a heap
(2) Remove the largest element in turn and place it at the end of the array.
3. Analysis of various sorting algorithms
Copyright notice: This article blog original articles, blogs, without consent, may not be reproduced.
Algorithm part i:priority Queues