快速排序

# 简单实现快速排序


(1) 首先实现 Partition 函数,

          函数功能:实现快速排序算法的关键在于在数组中选择一个数字,接下来把数组中的数字分为两部分,比选择

的数字小的数字一道数组的左边,比选择数字大的数字一道数 组的右边;

(2) 实现QuickSort 函数;

          函数功能: 调用Partition 函数,递归的实现快速排序;
  
注意:算法中调用RandomInRange函数(随机产生start 和end 中间的一个数) 和 Swap 函数(交换两个数的 容);


# 代码实现: 

#include<stdio.h>
#include<stdlib.h>

int Partition(int data[], int length, int start, int end)
{
	int index;
	int Small;

	if(data == NULL || length <= 0 || start < 0 || end >= length)
		return ;
	index = RandomInRange(start, end);
	//RandomInRange 是随机产生start和end中间的一个数;

	Swap(&data[index], &data[end]);
	//Swap 是交换两个数的函数;

	Small = start -1;
	for(index = start; index < end; ++index)
	{
		if(data[index] < data[end])
		{
			++Small;
			if(Small != index)
				Swap(&data[index], &data[Small]);
		}
	}
	++Small;
	Swap(&data[Small], &data[end]);

	return Small;
}

void QuickSort(int data[],int length, int start, int end)
{
	int index;

	if(start == end)
		return ;
	index = Partition (data, length, start, end);

	if(index > start)
		QuickSort (data, length, start, index - 1);
	if(index < end)
		QuickSort(data, length, index -1, end);
}

int main()
{
	int arr[] = {3,2,5,4,6,2,3,7,8,1};
	QuickSort(arr,10,0,9);
	//调用时 start 传 0,end 传length - 1;
	system("pause");
	return 0;
}




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值