对随机产生的数列进行快速排序

以前在学习快速排序的时候总是理解不够,导致总是没办法记住其使用方法,趁有空重新学习了一下快速排序,作此记录放遍日后复习及改进。代码如下:

#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;
}

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值