C語言實(shí)現(xiàn)堆排序的簡(jiǎn)單實(shí)例
更新時(shí)間:2014年07月04日 18:07:46 投稿:shichen2014
這篇文章主要介紹了C語言實(shí)現(xiàn)堆排序的簡(jiǎn)單實(shí)例,講述了堆排序的原理,需要的朋友可以參考下
本文通過一個(gè)C語言實(shí)現(xiàn)堆排序的簡(jiǎn)單實(shí)例,幫助大家拋開復(fù)雜的概念,更好的理解堆排序。
實(shí)例代碼如下:
void FindMaxInHeap(int arr[], const int size) {
for (int j = size - 1; j > 0; --j) {
int parent = j / 2;
int child = j;
if (j < size - 1 && arr[j] < arr[j+1]) {
++child;
}
if (arr[child] > arr[parent]) {
int tmp = arr[child];
arr[child] = arr[parent];
arr[parent] = tmp;
}
}
}
void HeapSort(int arr[], const int size) {
for (int j = size; j > 0; --j) {
FindMaxInHeap(arr, j);
int tmp = arr[0];
arr[0] = arr[j - 1];
arr[j - 1] = tmp;
}
}
int main()
{
int arr[] = {2, 5, 3, 12, 6, 21, 8, 1};
int n = sizeof(arr) / sizeof(arr[0]);
HeapSort(arr, n);
for (int j = 0; j < n; ++j) {
printf("%3d",arr[j]);
}
printf("\n");
return 0;
}
相關(guān)文章
C語言 ffmpeg與sdl實(shí)現(xiàn)播放視頻同時(shí)同步時(shí)鐘詳解
使用ffmpeg和sdl實(shí)現(xiàn)播放視頻后,需要再實(shí)現(xiàn)時(shí)鐘同步才能正常的播放視頻,尤其是有音頻的情況,我們通常需要將視頻同步到音頻來確保音畫同步2022-09-09
C語言 數(shù)據(jù)結(jié)構(gòu)中棧的實(shí)現(xiàn)代碼
這篇文章主要介紹了C語言 數(shù)據(jù)結(jié)構(gòu)中棧的實(shí)現(xiàn)代碼的相關(guān)資料,需要的朋友可以參考下2016-10-10
在vscode中快速新建html文件的2種方法總結(jié)
這篇文章主要給大家介紹了關(guān)于在vscode中快速新建html文件的2種方法,以及如何快速打開HTML文件查看編輯效果的方法,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2022-04-04
C++實(shí)現(xiàn)LeetCode(228.總結(jié)區(qū)間)
這篇文章主要介紹了C++實(shí)現(xiàn)LeetCode(228.總結(jié)區(qū)間),本篇文章通過簡(jiǎn)要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-07-07

