/*
2013年10月3日
by--acton
優先級隊列:1.最大優先級隊列的一個應用是在一臺分時的計算機上進行作業調度,
這種隊列要執行的各個作業及它們之間的的相對優先的關係加以記錄,
當一個作業完成或者中斷的時候,用Extract_Max將其從就緒的要執行的隊列中remove掉,
然後對這個堆進行再次的建立一個大頂堆,然後選出優先級相對較高的程序進行執行,
在任何時候一旦有一個作業進入就緒狀態,則將其加入到這個隊列當中 use Insert fuction。
2.最小優先級隊列的建立,相應的option 包括Insert ,Minmum,Extract_Min 和Decrease_key等,
這種隊列一般用於基於事件驅動的模擬器中。在這種應用中,隊列中的各項是要模擬的事件,每一個都有發生的時間作爲關鍵字,
事件模擬器要按各事件發生的時間順序進行,因爲模擬某一事件可能導致稍後對其他事件的模擬。模擬程序每次都要在每一部用Extract_Min
選擇下一個需要模擬的事件。當產生一個新的事件之後使用Insert將其加入到隊列中
*/
# include <stdio.h>
# include <stdlib.h>
# define INIT_HEAP_SIZE 7
# define INFINITY 99999
# define MAX_HEAP_SIZE 20
# define test_main main
int Heap_Size = INIT_HEAP_SIZE - 1; // the global varible to define the Heap_Size as the init heap_size ,
//but it will change with the dynamic options
int parent(int i){
return i/2;
}
int Left(int i ){
return i*2;
}
int Right(int i){
return i*2+1;
}
void Exchange(int * p, int * q){
*q = *q + *p;
*p = *q - *p;
*q = *q - *p;
}
void Max_Heapfy(int S[], int i){
int l = Left(i);
int r = Right(i);
int maxer;
if(l <= Heap_Size && S[i] < S[l]){
maxer = l ;
}else{
maxer = i ;
}
if(r <= Heap_Size && S[maxer] < S[r]){
maxer = r;
}
if(maxer != i){
Exchange(&S[maxer],&S[i]);
Max_Heapfy(S,maxer);
}
}
void Increase_Key(int S[], int i , int key){ //將元素X的關鍵字的值增加到K,這裏的K值不能小於X的原來的關鍵字的值
if (key < S[i]){
printf("the value key is little than the value in the location i\n");
return ;
}
S[i] = key;
while (i >= 0 && S[parent(i)] < S[i]){ //adjust to the root or the the parent is larger than
//the children specifically is the the newly insert key
Exchange(&S[i],&S[parent(i)]);
i = parent(i);
}
}
void Insert(int * S, int x){ //把元素X插入集合S,這一操作可以寫爲S = S U X;
Heap_Size ++ ;
S[Heap_Size] = - INFINITY ;
Increase_Key(S,Heap_Size,x);
//return S;
}
int MaxiMum(int S[]){ //返回S中具有最大關鍵字的元素
return S[0];
}
int Extract_Max(int* S){ //去掉並返回S中的具有最大關鍵字的元素
//運行的時間的複雜度爲O(lgn)
if (Heap_Size < 1){
printf("Heap underflow\n");
return -INFINITY;
}
int max = S[0];
S[0] = S[Heap_Size];
Heap_Size -- ;
Max_Heapfy(S,0);
return max;
}
void Build_Max_Heap(int S[]){
for (int i = Heap_Size /2 ; i >= 0 ; i -- ){
Max_Heapfy(S,i);
}
for (i = 0 ; i <= Heap_Size ; i ++ ){
printf("%5d ",S[i]);
}
putchar(10);
}
int test_main(void){
/*int * S = (int * )malloc(sizeof(int)* INIT_HEAP_SIZE);
if(!S){
printf("memery error!\n");
exit(-1);
}*/
int S[MAX_HEAP_SIZE] = {4,1,2,7,6,9,10};
Build_Max_Heap(S);
printf("MAXMUM of S is %d \n",MaxiMum(S));
// printf("MAXMUM return is %d \n",Extract_Max(S)); // 此時會將堆中的最大元素踢走 然後重新對堆進行調整
Insert(S,-1);
printf("MAXMUM of S is %d \n",MaxiMum(S));
printf("\nhello");
for (int i = 0 ; i <= Heap_Size ; i ++ ){
printf("%5d ",S[i]);
}
putchar(10);
return 0;
}