堆排序的實現

2022-09-17 12:06:16 字數 2847 閱讀 9610

堆排序的實現

在順序結構上完成,先建堆然後重建堆,最後實現全部排序

(個人作法,僅供參考)

#include

#include

#define max 100000

void heapadjust(int heap,int k,int m)

int i,j,finished;

int temp;

temp=heap[k];

i=k;

j=2*i;

finished=false;

while(j<=m&&!finished)

if(jheap[j+1])j=j+1;//篩選

if(temp<=heap[j])finished=true;

else

heap[i]=heap[j];

i=j;

j=2*i;

heap[i]=temp;

void heapadjust2(int heap,int k,int m)

int i,j,finished;

int temp;

temp=heap[k];

i=k;

j=2*i;

finished=false;

while(j<=m&&!finished)

if(jif(temp>=heap[j])finished=true;

else

heap[i]=heap[j];

i=j;

j=2*i;

heap[i]=temp;

void createheap(int heap,int length)

int i,n=length;

for(i=n/2;i>=1;--i)

heapadjust(heap,i,n);

void createheap2(int heap,int length)

int i,n=length;

for(i=n/2;i>=1;--i)

heapadjust2(heap,i,n);

void heapsort(int heap,int length)//對heap[1...n]進行堆排序

int temp,i,n;

createheap(heap,length);

n=length;

for(i=n;i>=2;--i)

temp=heap[1];//將堆頂記錄和堆中的最後乙個記錄互換

heap[1]=heap[i];

heap[i]=temp;

heapadjust(heap,1,i-1);//進行調整,使heap[1...i-1]變成堆

void heapsort2(int heap,int length)//對heap[1...n]進行堆排序

int temp,i,n;

createheap2(heap,length);

n=length;

for(i=n;i>=2;--i)

temp=heap[1];//將堆頂記錄和堆中的最後乙個記錄互換

heap[1]=heap[i];

heap[i]=temp;

heapadjust2(heap,1,i-1);//進行調整,使heap[1...i-1]變成堆

void printfheap(int heap,int length)

int i;

for(i=1;i<=length;i++)

printf("%d ",heap[i]);

printf("\n");

int main()

{system("color cf");  

int heap[max];

int n,i,choice;

printf("        堆排序功能選項\n");

printf("  1.輸入乙個新序列並進行堆排序\n");

printf("  2.輸出當前序列大頂堆排序\n");

printf("  3.輸出當前序列小頂堆排序\n");

printf("  4.退出堆排序\n");

loop1: printf("請選擇你的操作:");

scanf("%d",&choice);

switch(choice)

loop2: case 1:

printf("請輸入序列的個數:");

scanf("%d",&n);

printf("請依次輸入將要進行堆排序的元素:\n");

for(i=1;i<=n;i++)

scanf("%d",&heap[i]);

heap[0]=n;

goto loop1;

loop3: case 2: 

heapsort(heap,n);

printf("從大到小排序:\n");

printfheap(heap,heap[0]);

goto loop1; 

loop4: case 3:   

heapsort2(heap,n);

printf("從小到大排序:\n");

printfheap(heap,heap[0]);

goto loop1;       

case 4: printf("歡迎再來\n"); break;

2.功能介面

堆排序的實現

堆排序是利用了一種資料結構叫做二叉堆,二叉堆是這樣定義的 二叉堆是一種特殊的堆,二叉堆是完全二元樹或者是近似完全二元樹,有最小堆和最大堆 特點 1 父結點的鍵值總是大於或等於 小於或等於 任何乙個子節點的鍵值。2 每個結點的左子樹和右子樹都是乙個二叉堆 都是最大堆或最小堆 利用堆排序資料的儲存方式如...

堆排序的實現

file binaryheap.hpp brief 二叉堆 author xiao2 joyjj0218 qq.com version 1.0 date 2015.11.17 ifndef binaryheap hpp define binaryheap hpp include include us...

堆排序的實現

要想用堆來實現排序,首先得構建乙個堆。將字串 sortexample 放入起始下標為1的陣列中,構成一顆二叉樹 構造堆時,從最後乙個非葉子節點出發。如上圖所示,最後乙個非葉子節點下標為n 2 5,可以觀察出任意乙個大小為n的二叉堆的最後乙個非葉子節點的標號都是n 2。從5開始一直到根節點1,一直進行...