快速排序(Quick Sort)

         快速排序的基本思想是:通过一趟排序将待排记录分割成独立的两部分,其中一部分记录的关键字均比另一部分的关键字小,则可分别对这两部分记录继续进行排序,以达到整个序列有序的目的。

#include <iostream>
using namespace std;

void Swap(int *L, int i, int j)  
{  
		int temp = L[i];  
		L[i] = L[j];  
     	L[j] = temp;  
}  

int Partition(int *L, int low, int high)
{
	int pivotkey;
	pivotkey = L[low];
	while (low<high)
	{
		while(low < high && L[high] >= pivotkey)
		{
			high--;
		}
		Swap(L,low,high);
		while(low < high && L[low] <= pivotkey)
		{
			low++;
		}
		Swap(L,low,high);
	}
	return low;
}

void QSort(int *L, int low, int high)
{
	int pivot;
	if (low < high)
	{
		pivot = Partition(L,low,high);
		QSort(L,low,pivot-1);
		QSort(L,pivot+1,high);
	}
}

/*
void QuickSort(int *L, int n)
{
	QSort(L,0,n);
}*/

int main()
{
    int L1[9] = {9,1,5,8,3,7,4,6,2};
	int L2[9] = {50,10,90,30,70,40,80,60,20};
    QSort(L1,0,8);//n=9
	for (int i = 0; i<9; i++)
	{
		cout<<L1[i]<<" ";
	}
	cout<<endl;
	getchar();
	return 0;
}
结果:

时间复杂度为:O(N*logN)

相关:

白话经典算法系列之六 快速排序 快速搞定


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值