C语言实现堆排序代码

2018-07-20    来源:open-open

容器云强势上线!快速搭建集群,上万Linux镜像随意使用
void heapsort(int arr[], unsigned int N) 
{ 
    unsigned int n = N, i = n/2, parent, child; 
    int t; 
   
    for (;;) { /* Loops until arr is sorted */ 
        if (i > 0) { /* First stage - Sorting the heap */ 
            i--;           /* Save its index to i */ 
            t = arr[i];    /* Save parent value to t */ 
        } else {     /* Second stage - Extracting elements in-place */ 
            n--;           /* Make the new heap smaller */ 
            if (n == 0) return; /* When the heap is empty, we are done */ 
            t = arr[n];    /* Save last value (it will be overwritten) */ 
            arr[n] = arr[0]; /* Save largest value at the end of arr */ 
        } 
   
        parent = i; /* We will start pushing down t from parent */ 
        child = i*2 + 1; /* parent's left child */ 
   
        /* Sift operation - pushing the value of t down the heap */ 
        while (child < n) { 
            if (child + 1 < n  &&  arr[child + 1] > arr[child]) { 
                child++; /* Choose the largest child */ 
            } 
            if (arr[child] > t) { /* If any child is bigger than the parent */ 
                arr[parent] = arr[child]; /* Move the largest child up */ 
                parent = child; /* Move parent pointer to this child */ 
                //child = parent*2-1; /* Find the next child */ 
                child = parent*2+1; /* the previous line is wrong*/ 
            } else { 
                break; /* t's place is found */ 
            } 
        } 
        arr[parent] = t; /* We save t in the heap */ 
    } 
} 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点!
本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。

上一篇:仿IPhone从底部弹出选项菜单

下一篇:矩阵相乘C++代码