?? 快速排序.cpp
字號(hào):
//* * * * * * * * * * * * * * * * * * * * * * * *
//*CHAPTER :7 (7_4) *
//*PROGRAM :快速排序 *
//*CONTENT :快速排序 *
//* * * * * * * * * * * * * * * * * * * * * * * *
#include <dos.h>
#include <conio.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 20 //排序表的最大容量
typedef struct //定義排序表的結(jié)構(gòu)
{int elemword[MAXSIZE]; //數(shù)據(jù)元素關(guān)鍵字
int count; //表中當(dāng)前元素的個(gè)數(shù)
}SqList;
void InitialSqList(SqList&); //初始化排序表
void QuickSort(SqList &); //快速排序
void QSort(SqList &,int,int); //子序列快速排序
int Partition(SqList &,int,int); //一趟快速排序
void PrintSqList(SqList); //顯示表中的所有元素
void main()
{SqList L; //聲明表L
char j='y';
textbackground(3); //設(shè)定屏幕顏色
textcolor(15);
clrscr();
//-------------------------程序說明-------------------------------
printf("本程序?qū)⒀菔究焖倥判虻牟僮鳌n");
//----------------------------------------------------------------
while(j!='n'&&j!='N')
{InitialSqList(L); //待排序列初始化
QuickSort(L); //快速排序
PrintSqList(L); //顯示排序結(jié)果
printf("繼續(xù)進(jìn)行下一次排序嗎?(Y/N)");
scanf(" %c",&j);
}
printf("程序運(yùn)行結(jié)束!\n按任意鍵關(guān)閉窗口!\n");
getchar();getchar();
}
void InitialSqList(SqList &L)
{//表初始化
int i;
printf("請(qǐng)輸入待排序的記錄的個(gè)數(shù):");
scanf("%d",&L.count);
printf("請(qǐng)輸入待排序的記錄的關(guān)鍵字(整型數(shù)):\n");
for(i=1;i<=L.count;i++)
scanf("%d",&L.elemword[i]);
}
void QuickSort(SqList &L)
{//對(duì)順序表L做快速排序。
QSort(L,1,L.count);
}
void QSort(SqList &L,int low,int high)
{//對(duì)順序表中的子序列L.r[low..high]作快速排序
int pivotloc;
if(low<high) //長度大于1
{pivotloc=Partition(L,low,high); //將L.elemword[low..high]一分為二
QSort(L,low,pivotloc-1); //對(duì)低子表遞歸排序,pivotloc是樞軸位置
QSort(L,pivotloc+1,high); //對(duì)高子表遞歸排序
}
}
int Partition(SqList &L,int low,int high)
{//交換順序表L中子表r[low..high]的記錄,樞軸記錄到位,并返回其所在位置,此時(shí)
//在它之前(后)的記錄均不大(小)于它
int pivotkey;
pivotkey=L.elemword[low]; //用子表的第一個(gè)記錄作樞軸記錄
while(low<high) //從表的兩端交替地向中間掃描
{while(low<high&&L.elemword[high]>=pivotkey)
--high;
L.elemword[low]=L.elemword[high];//將比樞軸記錄小的記錄移到低端
while(low<high&&L.elemword[low]<=pivotkey)
++low;
L.elemword[high]=L.elemword[low]; //將比樞軸記錄大的記錄移到高端
}
L.elemword[low]=pivotkey; //樞軸記錄到位
return low; //返回樞軸記錄
}
void PrintSqList(SqList L)
{//顯示表中所有元素
int i;
printf("已排好序的序列如下:\n");
for(i=1;i<=L.count;i++)
printf("%4d",L.elemword[i]);
printf("\n");
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -