快速排序,归并排序

/*
Title:快速排序,归并排序
Author:Liu Xiaodong
*/
#include
#include
#define Maxnum 100
typedef int KeyType;
typedef struct
{
KeyType key;
}Node;
typedef struct
{
Node num[Maxnum];
int length;
}SqList;
int Compare(int a,int b)
{
if(a<=b)
return 1;
}
//QuickSort

int Partition(SqList &L,int low,int high)
{
KeyType pivotkey;
L.num[0]=L.num[low];
pivotkey=L.num[low].key;
while(low{
while(low=pivotkey)
--high;
L.num[low]=L.num[high];
while(low++low;
L.num[high]=L.num[low];
}
L.num[low]=L.num[0];
return low;
}
void QSort(SqList &L,int low,int high)
{
int pivotloc;
if(low{
pivotloc=Partition(L,low,high);
QSort(L,low,pivotloc-1);
QSort(L,pivotloc+1,high);
}
}
void QuickSort(SqList &L)
{
QSort(L,1,L.length);
}

//mergeSort
void Merge(Node SR[],Node TR[],int i,int m,int n)
{
int j,k;
for(j=m+1,k=i;i<=m&&j<=n;++k)
{
if(SR[i].keyTR[k]=SR[i++];
else
TR[k]=SR[j++];
}
if(i<=m)
while(i<=m)
TR[k++]=SR[i++];
if(j<=m)
while(j<=m)
TR[k++]=SR[j++];
}
void MSort(Node SR[],Node TR1[],int s,int t)
{
Node TR2[50];
int m;
if(s==t)
TR1[s]=SR[s];
else
{
m=(s+t)/2;
MSort(SR,TR2,s,m);
MSort(SR,TR2,m+1,t);
Merge(TR2,TR1,s,m,t);
}
}

void MergeSort(SqList &L)
{
MSort(L.num,L.num,1,L.length);
}


int main()
{
SqList L;

int i=1,j;
int n;
for(j=0;jL.num[j].key=0;
printf("please input the number of the data you want input:\n");
scanf("%d",&n);
printf("*********QuickSort****************\n");
printf("please input the data:\n");
while(i<=n)
scanf("%d",&L.num[i++].key);
L.length=n;
printf("The result of the QuickSort :\n");
QuickSort(L);
j=1;
while(j<=n)
printf("%d ",L.num[j++].key);

printf("*********归并排序****************\n");
printf("please input the data:\n");
while(i<=n)
scanf("%d",&L.num[i++].key);
L.length=n;
MergeSort(L);
j=1;
while(j<=n)
printf("%d ",L.num[j++].key);
return 0;

}

相关文档
最新文档