C语言实现堆排序代码
发布时间:2020-12-16 07:45:56 所属栏目:百科 来源:网络整理
导读:今天PHP站长网 52php.cn把收集自互联网的代码分享给大家,仅供参考。 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
以下代码由PHP站长网 52php.cn收集自互联网 现在PHP站长网小编把它分享给大家,仅供参考 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 */ } } 以上内容由PHP站长网【52php.cn】收集整理供大家参考研究 如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |