堆排序2——优先级队列

优先级队列是一种用来维护有一组元素构成的集合S数据结构,这一组元素中的每一个都有一个关键字key

主要有以下的操作

INSERT(S,x)  

MAXIMUM(S)

EXTRACT-MAX(S)

INCREASE-KEY(S,x,k),将元素x的关键字的值增加到k,这里k值不能小于x的原关键字的值。

 #include <iostream>
 using namespace std;
 const int INF = 999999;
  
 void MaxHeapify(int *a, int i, int len)
 {
     int lt = 2*i, rt = 2*i+1;
     int largest;
     if(lt <= len && a[lt] > a[i])
         largest = lt;
     else
         largest = i;
     if(rt <= len && a[rt] > a[largest])
         largest = rt;
     if(largest != i)
     {
         int temp = a[i];
         a[i] = a[largest];
         a[largest] = temp;
         MaxHeapify(a, largest, len);
     }
 }
  
 void BuildMaxHeap(int *a, int size)
 {
     for(int i=size/2; i>=1; --i)
         MaxHeapify(a, i, size);
 }
  
 void PrintArray(int data[], int size)
 {
     for (int i=1; i<=size; ++i)
         cout <<data[i]<<"  ";
     cout<< endl << endl;
 }
 
  
 // 返回具有最大关键字的元素
 int HeapMaximum(int *a)
 {
     return a[1];
 }
  
 // 去掉并返回具有最大关键字的元素
 // 注意:这里每次MaxHeapify的是heapsize
 int HeapExtractMax(int *a, int &heapsize)
 {
     if(heapsize < 1)
         cout << "Heap Underflow" << endl;
     int max = a[1];
     a[1] = a[heapsize];
     --heapsize;
     MaxHeapify(a, 1, heapsize);
     return max;
 }
  
 // 将元素a[i]的值增加到key
 void HeapIncreaseKey(int *a, int i, int key)
 {
     if(key < a[i])
         cout << "New key is smaller than current key" << endl;
     a[i] = key;
     while(i > 1 &&a[i/2] < a[i])
     {
         int temp = a[i];
         a[i] = a[i/2];
         a[i/2] = temp;
         i /= 2;
     }
 }
  
 // 插入关键字为key的元素
 void MaxHeapInsert(int *a, int key, int &heapsize)
 {
     ++heapsize;
     a[heapsize] = -INF;
     HeapIncreaseKey(a, heapsize, key);
 }
  
  
  
 int main()
 {
     int len, heapsize;
     int arr[100] = {0, 15, 13, 9, 5, 12, 8, 7, 4, 0, 6, 2, 1};
     // 区别len 和 heapsize
     // heapsize是堆的大小,而len是初始数组的总大小。
     len = heapsize = 12;
  
     // 首先建堆
     BuildMaxHeap(arr, len);
     cout << "建堆后: " << endl;
     PrintArray(arr, len);
  
     // 使用HeapMaximum
     cout << "当前最大的元素是: " << endl;
     cout << HeapMaximum(arr) << endl << endl;
  
     // 使用HeapExtractMax
     cout << "使用HeapExtractMax后: " << endl;
     HeapExtractMax(arr,heapsize);
     PrintArray(arr, heapsize);
  
     // 再次使用HeapExtractMax
     cout << "再次使用HeapExtractMax后: " << endl;
     HeapExtractMax(arr,heapsize);
     PrintArray(arr, heapsize);
  
     // 使用HeapIncreaseKey
     cout << "使用HeapIncreaseKey后: " << endl;
     HeapIncreaseKey(arr, 2, 15);
     PrintArray(arr, heapsize);
  
     // 使用MaxHeapInsert
     cout << "使用MaxHeapInsert后: " << endl;
     MaxHeapInsert(arr, 28, heapsize);
     PrintArray(arr, heapsize);
 }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值