排序算法-快速排序(nlogn)

快速排序

代码:

#include<iostream>
#include<string>

using namespace std;
int Partition(int a[], int low, int high);
void QuickSort(int a[], int low, int high);

int main()
{
	int buff[7] = { 5, 2, 1, 4, 9, 6, 0 };
	for (int i = 0; i < 7; i++)
		cout << buff[i] ;
	cout << endl;
	QuickSort(buff, 0, 6);
	for (int i = 0; i < 7; i++)
		cout << buff[i];
	cout << endl;
	return 0;
}

int Partition(int a[], int low, int high)
{
	int x = a[high];//将输入数组的最后一个数作为主元,用它来对数组进行划分
	int i = low - 1;//i是最后一个小于主元的数的下标
	for (int j = low; j < high; j++)//遍历下标由low到high-1的数
	{
		if (a[j] < x)//如果数小于主元的话就将i向前挪动一个位置,并且交换j和i所分别指向的数
		{
			int temp;
			i++;
			temp = a[i];
			a[i] = a[j];
			a[j] = temp;
		}
	}
	//经历上面的循环之后下标为从low到i(包括i)的数就均为小于x的数了,现在将主元和i+1位置上面的数进行交换
	a[high] = a[i + 1];
	a[i + 1] = x;
	return i + 1;
}
void QuickSort(int a[], int low, int high)
{
	if (low < high)
	{
		int q = Partition(a, low, high);
		QuickSort(a, low, q - 1);
		QuickSort(a, q + 1, high);
	}
}

结果:


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值