通过补全快速排序私有函数QSort__来供函数QuickSort调用,以此来实现快速排序的功能。
相关知识
快速排序的基本过程是:从待排序记录中任选一个记录,以它的排序码作为中心值,将其它记录划分为两个部分,第一部分包含所有排序码小于等于中心值的记录,第二部分包含所有排序码大于中心值的记录。第一部分放在该记录的前面,第二部分放在该记录的后面。对这两个部分采用同样的方法进行处理,直到每个部分为空或只含一个记录为止。
下图 1 给出了一个用中心值将排序记录分割为前后两部分的示例过程。
输入输出格式说明
输入格式:
首先输入一个正整数n。
然后输入n个整数。
输出格式:
输出对 n 个整数从小到大排序的结果。
以下是平台对 step1/Main.cpp 的样例测试集:
样例输入:
5
45 78 2 34 90
样例输出:
sort result:2 34 45 78 90
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include"quickSort.h"
void QSort__(int* a, int low, int high)
//快速排序私有函数,供QuickSort()调用
//在a[low:high]中选择一个中心值,用该中心值将a[low:high]分割为两部分
//然后对两个部分递归地进行该操作。
{
int i, j;
if(low>=high)
{
return;
}
Swap(a[low], a[rand()%(high-low+1)+low]); //select a pivot randomly
i=low;
j=high;
int temp=a[i];
while (i<j)
{
while (i<j && temp<a[j])
{
j--;
}
if(i<j)
{
a[i++]=a[j];
}
while (i<j && a[i]<=temp)
{
i++;
}
if(i<j)
{
a[j--]=a[i];
}
}
a[i]=temp;
QSort__(a, low, i-1);
QSort__(a, i+1, high);
}
void QuickSort(int* a, int n)
//快速排序主函数
{
srand((unsigned)time(0)); //for selecting the pivot randomly in QSort__().
QSort__(a, 0, n-1);
}
void SortPrint(int* a, int n)
{
int i;
printf("sort result:");
for(i=0;i<n;i++)
{
printf("% d",a[i]);
}
//printf("\n");
}
int main()
{
int n;
scanf("%d", &n);
int i;
int *a=(int*)malloc(sizeof(int)*n);
for (i=0; i<n; i++)
{
scanf("%d", &a[i]);
}
QuickSort(a,n);
SortPrint(a,n);
//system("PAUSE");
//free(a);
}