Binary Tree-Max heap

Source: Internet
Author: User

Binary Tree-Max heap

Maxheap. h

#include 
 
  template 
  
   class MaxHeap{public:MaxHeap(int num);MaxHeap(T Arr[], int arrsize, int totalsize);bool insert(const T&);bool del(T&);void show() const;void showonlevel() const;private:T* arr;int size, max_size;};template 
   
    MaxHeap
    
     ::MaxHeap(int num){arr = new T [num + 1];max_size = num;size = 0;}template 
     
      MaxHeap
      
       ::MaxHeap(T Arr[], int arrsize, int totalsize){arr = new T [totalsize + 1];max_size = totalsize;size = arrsize;arr = Arr;int loc, cloc;for (loc = size/2; loc >= 1; --loc){T tmp = arr[loc];cloc = loc * 2;while (cloc <= size){if (cloc < size && arr[cloc + 1] > arr[cloc])++cloc;if (tmp > arr[cloc])break;arr[cloc/2] = arr[cloc];cloc *= 2;}arr[cloc/2] = tmp;}}template 
       
        bool MaxHeap
        
         ::insert(const T& val){if (size == max_size)return false;int num = ++size;while (num > 1 && val > arr[num/2]){arr[num] = arr[num/2];num /= 2;}arr[num] = val;return true;}template 
         
          bool MaxHeap
          
           ::del(T& val){if (size == 0)return false;val = arr[1];T tmp = arr[size--];int loc = 1, cloc = 2;while (cloc < size){if (cloc < size && arr[cloc + 1] > arr[cloc])++cloc;if (tmp > arr[cloc])break;arr[loc] = arr[cloc];loc = cloc;cloc *= 2;}arr[loc] = tmp;return true;}template 
           
            void MaxHeap
            
             ::show()const{for (int i = 1; i <= size; ++i)std::cout 
             
              ::showonlevel()const{int k = 1;for (int i = 1; i <= size; ++i){std::cout <
              

main.cpp

#include 
               
                #include "maxheap.h"int main(){MaxHeap
                
                  a(30);int c[32];for (int i = 1 ; i <= 30; i++){c[i] = rand();a.insert(c[i]);}a.showonlevel();std::cout <
                 
                   b(c, 30,40);b.showonlevel();std::cout <
                  
                   

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.