?? 堆排序.cpp
字號:
//* * * * * * * * * * * * * * * * * * * * * * * *
//*CHAPTER :7 (7_6) *
//*PROGRAM :堆排序 *
//*CONTENT :堆排序 *
//* * * * * * * * * * * * * * * * * * * * * * * *
#include <dos.h>
#include <conio.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 20 //排序表的最大容量
typedef struct //定義排序表的結構
{int elemword[MAXSIZE]; //數據元素關鍵字
int length; //表中當前元素的個數
}SqList;
void InitialSqList(SqList&); //初始化排序表
void HeapSort(SqList &); //堆排序
void HeapAdjust(SqList &,int,int); //堆調整
void PrintSqList(SqList); //顯示表中的所有元素
void main()
{SqList L; //聲明表L
char j='y';
// textbackground(3); //設定屏幕顏色
// textcolor(15);
//clrscr();
//-------------------------程序說明-------------------------------
printf("本程序將演示堆排序的操作。\n");
//----------------------------------------------------------------
while(j!='n'&&j!='N')
{InitialSqList(L); //待排序列初始化
HeapSort(L); //堆排序
PrintSqList(L); //顯示排序結果
printf("繼續進行下一次排序嗎?(Y/N)");
scanf(" %c",&j);
}
printf("程序運行結束!\n按任意鍵關閉窗口!\n");
getchar();getchar();
}
void InitialSqList(SqList &L)
{//表初始化
int i;
printf("請輸入待排序的記錄的個數:");
scanf("%d",&L.length);
printf("請輸入待排序的記錄的關鍵字(整型數):\n");
for(i=1;i<=L.length;i++)
scanf("%d",&L.elemword[i]);
}
void HeapSort(SqList &L)
{//對順序表L做堆排序。
int i,j,t;
for(i=L.length/2;i>0;--i) //把L.elemword[1..L.length]建成大頂堆
HeapAdjust(L,i,L.length);
for(i=L.length;i>1;--i)
{t=L.elemword[1]; //將堆頂記錄和當前未經排序子序列L.elemword[1..i]
L.elemword[1]=L.elemword[i]; //中的最后一個記錄相互交換
L.elemword[i]=t;
HeapAdjust(L,1,i-1); //將L.r[1..i-1]重新調整為大頂堆
}
}
void HeapAdjust(SqList &H,int s,int m)
{//已知H.elemword[s..m]中除H.elemword[s]之外均滿足堆的定義,本函數調整H.elemword[s]
//使H.elemword[s..m]成為一個大頂堆
int j,rc;
rc=H.elemword[s];
for(j=2*s;j<=m;j*=2) //沿關鍵字叫大的結點向下篩選
{if(j<m&&H.elemword[j]<H.elemword[j+1]) ++j; //j為關鍵字較大的記錄的下標
if(rc>=H.elemword[j]) break; //rc應插入在位置s上
H.elemword[s]=H.elemword[j];
s=j;
}
H.elemword[s]=rc; //插入
}
void PrintSqList(SqList L)
{//顯示表中所有元素
int i;
printf("已排好序的序列如下:\n");
for(i=1;i<=L.length;i++)
printf("%4d",L.elemword[i]);
printf("\n");
}
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -