面试准备排序算法之堆

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了面试准备排序算法之堆相关的知识,希望对你有一定的参考价值。

#include<stdio.h>

void Fix(int a[], int index);
int main(){

    int array[10] = { 1, 3, 6, 4, 19, 33, 10, 3, 8, 2 };

    Fix(array, 9);
    for (int i = 9; i >= 0; i--){

        int temp = array[i];
        array[i] = array[0];
        array[0] = temp;
        Fix(array, i-1);
    }

    for (int i = 0; i < 10; i++){

        printf("%d ", array[i]);
    }
}

void Fix(int a[], int index){

    for (int i = index; i >= 0; i--){
    
        int parent = (i - 1) / 2;
        if (parent >= 0){

            if (a[i] > a[parent]){
            
                int temp = a[i];
                a[i] = a[parent];
                a[parent] = temp;
            }
        }
    }
}

堆排序

http://www.cnblogs.com/mengdd/archive/2012/11/30/2796845.html

#include<stdio.h>

void Merge(int a[], int first, int end);
void Sort(int a[], int first, int mid, int end);

int temp[10];
int main(){


    int array[10] = { 1, 3, 6, 4, 19, 33, 10, 3, 8, 2 };

    Merge(array, 0, 9);

    for (int i = 0; i < 10; i++){

        printf("%d ", array[i]);
    }

    getchar();
}

void Merge(int a[], int first, int end){

    int mid = (first + end) / 2;
    if (mid != first)
        Merge(a, first, mid);
    if (mid != end)
        Merge(a, mid + 1, end);

    Sort(a, first, mid, end);
}

void Sort(int a[], int first, int mid, int end){

    int i = first, j = mid + 1, k = 0;
    while (i <= mid || j <= end){
    
        if (a[i] > a[j]){

            if (j > end){

                temp[k++] = a[i++];
            }
            else{

                temp[k++] = a[j++];
            }
        }
        else{

            if (i > mid){

                temp[k] = a[j++];
            }
            else{

                temp[k++] = a[i++];
            }
        }
    }

    for (int i = 0; i < k; i++){
        a[first + i] = temp[i];
    }
}

归并排序

http://www.cnblogs.com/Braveliu/archive/2013/01/14/2860456.html

http://baike.baidu.com/link?url=pphpIR22RnpSQO0AHPAfTFHGdm5Hk7yaM_JM5L3o_nYK8nmBwWL0dDTxrzA4ZZhNJjVYHIBpKaq-FlmPmzypQa

以上是关于面试准备排序算法之堆的主要内容,如果未能解决你的问题,请参考以下文章

基本功之堆排序与快排序

重温基础算法内部排序之堆排序法

重温基础算法内部排序之堆排序法

简易学算法之堆排序

算法排序算法之堆排序

十大经典排序之堆排序,被树耽误的数组