快速排序--个人思路与书本思路 (复习排序算法)

快速排序的平均时间最好,O(nlgn),最差的时候为每次选择的枢轴为第一个,相当于冒泡排序O(n^2)。空间复杂度 O(lgn);//利用的递归栈

自己的思路是:先选第一个为枢轴,然后从下一个元素开始进行划分,右边是大于的,左边是小于的。先进行比较,俩边进行,交换俩端不符合的,也即交换右边为大的,左端小的,之后继续,最后的时候要么刚好A[low] < pivot,则直接为枢轴位置,交换下即可,要么因为low 要回退一个,即low指向的下一个位置。

个人写的程序确实没有,书上的精简。

第二个函数思路:用俩端的数据填充因挖掉枢轴产生的空缺,并且最终刚好low == high时即为枢轴,刚好留下空缺直接填充即可。代码很精简!!

具体解释大家可以参考:http://blog.csdn.net/morewindows/article/details/6684558

#include <iostream>
#include <cassert>
#include <algorithm>
using namespace std;

int partition(int *A,int low,int high);
void qsort(int *A,int n);
int q_partition(int *A,int low,int high);
void q_sort(int *A,int n);
int main()
{
	int A[10] = {2,3,5,1,7,8,4,0,9,6};//{2,3,5,1,7,8,4,0,9,6};
    qsort(A,8);
	for (int i = 0;i < 8;i++)
	{
		cout<<A[i]<<endl;
	}
	
	cout<<"----------"<<endl;
	int B[10] = {2,3,5,1,7,8,4,0,9,6};
	q_sort(B,10);
	for (int i = 0;i < 10;i++)
	{
		cout<<B[i]<<endl;
	}
	return 0;
}

void qsort(int *A,int n)
{
	if (n <= 1)
	{
		return;
	}
	int index = partition(A,0,n-1);
	//cout<<"index:"<<index<<endl;
	qsort(A,index);
	qsort(A+index+1,n - index-1);
}

int partition(int *A,int low,int high)
{
	// 选第一个为枢轴,或者取第一个,最后一个,中间的一个元素的中间值
	assert(A&& low <= high && low >=0);
	if (low == high)
	{
		return low;
	}
	int pivot = A[low];
	int pivot_index = low;
	low = low + 1;
	while(low < high)
	{
		while(low < high && A[high] > pivot) high-- ;
		
		while(low < high && A[low] < pivot) low++;
		
		if (low < high)
		{
			swap(A[low],A[high]);
			low ++;
			high--;
		}
	}
	
	if (A[low] < pivot)
	{
		swap(A[low],A[pivot_index]);
	}
	else
	{
		low--;
		swap(A[low],A[pivot_index]);
	}
	
	return low;
}


void q_sort(int *A,int n)
{
	if (n <= 1)
	{
		return;
	}
	int index = q_partition(A,0,n-1);
	//cout<<"index:"<<index<<endl;
	q_sort(A,index);
	q_sort(A+index+1,n - index-1);
}
int q_partition(int *A,int low,int high)
{
	assert(A&& low <= high && low >=0);
	//挖空
	int pivot = A[low];

	while(low < high)
	{
		while(low < high && A[high] > pivot) high -- ;
		A[low] = A[high];// 填空缺
		while(low < high && A[low] < pivot) low ++;
		A[high] = A[low];
	}
	
	A[low] = pivot;
	return low;

}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值