以前在学习快速排序的时候总是理解不够,导致总是没办法记住其使用方法,趁有空重新学习了一下快速排序,作此记录放遍日后复习及改进。代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define ERROR -1
int createRand(const int start, const int end, const int count, int *buf);
int partition(int* buf, int low, int high);
int QSort(int *buf, int low, int high);
int main01()
{
int a[10];
//printf("the arry a size is : %d\n", sizeof(a)/sizeof(a[0]));
createRand(10, 20, sizeof(a) / sizeof(a[0]), a);
printf("this arry data is :\n");
for (int i = 0; i < sizeof(a) / sizeof(a[0]); i++)
printf("%d\n", a[i]);
printf("==========================================\n");
QSort(a, 0, 9);
printf("this arry data after quick sort is :\n");
for (int i = 0; i < sizeof(a) / sizeof(a[0]); i++)
printf("%d\n", a[i]);
system("pause");
return 0;
}
//start-end指定随机数的范围,buf 存放产生的随机数(列)
int createRand(const int start, const int end, const int count, int *buf)
{
if (abs(end - start + 1) < count)
{
printf("the count is too long that can't create \n"); //输入的范围超过数组的容量,报错
return ERROR;
}
//随机数产生的两个步骤:
//1、用srand((unsigned int)time(NULL)) 种下时间种子,
//这里强制转换成 unsigned int 是因为 time() 返回的是 int 型,而srand() 需要的参数是 unsigned int
//2、使用 rand() 产生随机数,rand() 使用公式:rand() % abs(end - start + 1) + start
srand((unsigned int)time(NULL)); //种下时间种子
for (int i = 0; i < count; ++i)
{
buf[i] = rand() % abs(end - start + 1) + start; //产生随机数
}
return 0;
}
//快速排序,先对数列进行分区
//buf是需要排序的数组首地址,low-high指定需要排序的范围
int partition(int* buf, int low, int high)
{
if (buf == NULL)
return ERROR;
int pivotKey = buf[low]; //把数组起始元素作为 枢轴记录
while (low < high) //此次循环后以 枢轴记录 为中心,两边是比 枢轴记录 小或大的值
{
while (low < high && pivotKey <= buf[high]) --high; //从高处查找比 枢轴记录 更小的值,如发现则交换
buf[low] = buf[high];
while (low < high && pivotKey >= buf[low]) ++low; //从低处查找比 枢轴记录 更大的值,如发现则交换
buf[high] = buf[low];
}
buf[low] = pivotKey; //把枢轴记录的数据填补到此次划分后的 枢轴位置
return low;
}
int QSort(int *buf, int low, int high)
{
if (buf == NULL)
return ERROR;
if (low < high)
{
int pivotKey = partition(buf, low, high);
QSort(buf, low, pivotKey - 1); //递归对 低值区 继续分区
QSort(buf, pivotKey + 1, high); //递归对 高值区 继续分区
}
return 0;
}