标签:
用顺序表保存输入的数据,再用快速排序法给输入的数据排序,并打印出每趟排序后的结果
#include<stdio.h>
#include<stdlib.h>
#include <conio.h>
#define LIST_INIT_SIZE 100
typedef int Status;
typedef int ElemType;
typedef struct{
ElemType *r; //存储空间基址
// struct A *r
int length; //当前长度
int listsize; //当前分配的存储容量(以sizeof(ElemType)为单位)
}SqList;
void InitList_Sq(SqList &L){ // 构造一个空的线性表L。
int i;
L.r = (ElemType *)malloc(LIST_INIT_SIZE * sizeof(ElemType));
if (!L.r) exit(0); //存储分配失败
L.length = 0; //空表长度为0
L.listsize = LIST_INIT_SIZE; //初始存储容量
printf("请输入初始线性表长度:n="); //输入线性表初始化时的长度
scanf("%d",&L.length);
printf("请输入位序从1到%d的各元素(整数),例如:2 4 5 6 7 ...\n");
for(i=0;i<L.length;i++)
scanf("%d",&L.r[i]); //输入线性表的各元素
}//InitList_Sq
Status FreeList_Sq(SqList &L){ // 构造一个空的线性表L。
free(L.r);
return 0;
}//FreeList_Sq
int Partition(SqList &L,int low,int high)
{
int pivotkey = L.r[low];
while(low<high)
{
if(low<high && L.r[high]>=pivotkey) --high;
L.r[low]=L.r[high];
if(low<high && L.r[low]<=pivotkey) ++low;
L.r[high]=L.r[low];
}
L.r[low]=pivotkey;
return low;
}
void ListDisplay_Sq(SqList L){
//显示当前线性表所有元素
int i;
for(i=0;i<L.length;i++)
printf("%3d",L.r[i]);
printf("\n");
}//ListDisplay_Sq
void QSort(SqList &L,int low ,int high,int i)
{
//对顺序表L中的子序列 r[low...high]做快速排序
int pivotloc;
if(low<high)
{
pivotloc=Partition(L,low,high);
printf("第%d趟排序结果:",i++);
ListDisplay_Sq(L);
QSort(L,low,pivotloc-1,i);//对左子表 递归排序
QSort(L,pivotloc+1,high,i);//对右子表 递归排序
}
}
main()
{
SqList L;
int i=1;
InitList_Sq(L);
int low=0;
int high=L.length-1;
QSort(L, low ,high,i);
FreeList_Sq(L);
}
标签:
原文地址:http://www.cnblogs.com/dawntodusk/p/4561879.html