算法導論第6章代碼之優先級隊列

這裏講述的是用堆實現的最大優先級隊列,創建的是最大堆,主要實現3個算法,一個是抽取對頭元素,也就是整個堆裏面最大的那個數,還有一個是提升某個節點的優先級,最後是往隊尾插入元素。算法


一、創建最大堆數組

void build_max_heap(int *a, int i, int n)
{
    int max = i;
    int left = 2 * i + 1;
    int right = 2 * i + 2;
                                              
    if (left < n && a[left] > a[max]) {
        max = left;
    }
                                              
    if (right < n && a[right] > a[max]) {
        max = right;
    }
                                              
    if (i != max) {
                                                  
        int temp = a[i];
        a[i] = a[max];
        a[max] = temp;
                                                  
        build_max_heap(a, max, n);
                                                  
    }
                                              
}


二、抽取對頭元素ide

int extract_max(int *a, int n)
{
    int max = a[0];
                                        
    a[0] = a[n-1];
    build_max_heap(a, 0, n-1);
                                        
    return max;
}


三、將隊列中的某個元素的優先級提升ui

int increase_key(int *a, int i, int key)
{
    if (key < a[i]) {
        return -1;
    }
                                
    a[i] = key;
    int p;
    while (i > 0 && a[p=(i-1)/2] < a[i]) {
                                    
        int temp = a[p];
        a[p] = a[i];
        a[i] = temp;
                                    
        i = p;
    }
                                
    return 0;
}

四、隊尾插入元素隊列

void heap_insert(int *a, int n, int key)
{
    int i = n;
    a[i] = key;
    int p;
                          
    while (i > 0 && a[p=(i-1)/2] < a[i]) {
                              
        int temp = a[p];
        a[p] = a[i];
        a[i] = temp;
                              
        i = p;
    }
                          
}


注意在插入的時候,要確保數組有足夠的存儲空間,n是當前數組元素的下一個位置it

相關文章
相關標籤/搜索