快排算法

// 快速排序算法实现
// 采用递归算法,每一趟排序下来都将整个数组分为
// 比基准元素小的部分和比基准元素大的部分
// 再对这两部分分别排序
#include<iostream>
using namespace std;
// 打印数组
void print(int a[], int n)
{
	for(int i=0; i<n; i++)
		cout<<a[i]<<" ";
	cout<<endl;
}
// 交换两个数组的值
void swap(int *a, int *b)
{
	int tmp=*a;
	*a=*b;
	*b=tmp;
}
// 将数组分为比基准元素小和比基准元素大的两个部分
int partition(int a[], int low, int high)
{
	int privotKey=a[low]; // 基准值取每个区的第一个元素
	while(low<high) // 如果low和high两个索引相等,则这趟排序结束
	{
		while(low<high && a[high]>=privotKey) // 从最后一个元素过来,如果比基准值大,继续往前移
		{
			high--;
		}
		swap(a[low], a[high]); // 否则,如果比基准小,则调换基准和该元素位置
		while(low<high && a[low]<=privotKey) // 从第一个元素过来,如果比基准值小,继续往后移
		{
			low++;
		}
		swap(a[low], a[high]); // 否则,如果比基准大 ,则调换基准和该元素位置
	}
	return low;
}
void quickSort(int a[], int low, int high)
{
	if(low<high)
	{
		int privotLoc=partition(a, low, high); // 第一趟排序分左边区右边区
		quickSort(a, low, privotLoc-1); // 递归排序左边区
		quickSort(a, privotLoc+1, high); // 递归排序右边区
	}
}
int main()
{
	int a[]={1, 2, 3, 4};
	int num=sizeof(a)/sizeof(a[0]);
	cout<<"进行快速排序的整数个数:"<<num<<endl;
	cout<<"初始值为:";
	print(a, num);
	quickSort(a, 0, num-1);
	cout<<"结果为:";
	print(a, num);
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值