文章参考过网上的内容,如有侵权,请联系
#include<stdio.h>
#include<stdlib.h>
typedef struct
{
int *data; //线性链表的初值
int length;
}Sqlist;
int Partition2(Sqlist &L,int low,int high)
{//交换顺序表L中子表r[low..high]的记录,枢纽记录到位,并返回其所在位置
//在它之前(后)的记录均不大(小)于它
L.data[0]=L.data[low]; //用子表第一个记录作枢纽记录
int key =L.data[low]; //枢纽记录关键字
while(low<high){
while(low<high&&L.data[high]>=key)
--high; //从右向左搜索
L.data[low]=L.data[high];//移动比枢纽记录值小的记录
while(low<high&&L.data[low]<=key)
++low;//从左往右搜索
L.data[high]=L.data[low];//将比枢纽记录大的记录移到高端
}
L.data[low]=L.data[0];
return low;
}
void Qsort(Sqlist &L,int low,int high)
{ //对顺序表L中的子序列L.r[low..high]作快速排序
if(low<high){ //长度大于一
int pivotloc=Partition2(L,low,high); //将子序列一分为二
Qsort(L,low,pivotloc-1); //对低子表递归排序
Qsort(L,pivotloc+1,high); //对高子表递归排序
}
}
void BInserSort(Sqlist &L)
{ //对顺序表L作折半插入排序
int i;
for(i=2;i<=L.length;++i){
L.data[0]=L.data[i]; //将L.r[i]暂存到L.r[0]
int low=1; int high=i-1;
while(low<=high){ //在序列中折半查找插入位置
int m=(low+high)/2;
if(L.data[0]<L.data[m]) high=m-1; //插入点在低半区
else low=m+1; //插入点在高半区
}
for(int j=i-1;j>=high+1;--j) L.data[j+1]=L.data[j]; //记录后移
L.data[high+1]=L.data[0]; //插入
}
}
int main()
{
int a[8]={0,1,6,4,10,5,3,2};
Sqlist L;
L.length=7;
L.data=a;
for(int i=1;i<=L.length;i++) printf("%d ",L.data[i]);
printf("\n");
printf("-----------进行快速排序--------\n");
Qsort(L,1,7);
for(int i=1;i<=L.length;i++) printf("%d ",L.data[i]);
printf("\n");
printf("-------进行折半插入排序---------\n");
BInserSort(L);
for(int i=1;i<=L.length;i++) printf("%d ",L.data[i]);
}