漫画算法笔记 快速排序

漫画算法笔记

快速排序

#include <iostream>
#include <stdlib.h>
#include <iterator>
#include <vector>
#include <map>
#include <stack>
using namespace std;

//单边循环法
template<typename T>
int partition1(vector<T> &vec, int startIndex, int endIndex)
{
	T pivot = vec[startIndex];
	int mark = startIndex;

	for (int i = startIndex + 1; i <= endIndex; ++i)
	{
		if ( vec[i] < pivot )
		{
			mark++;
			if ( mark != i )
			{
				using namespace std;
				swap(vec[mark], vec[i]);
			}
		}
	}
	
	vec[startIndex] = vec[mark];
	vec[mark] = pivot;
	return mark;
}

//双边循环法
template<typename T>
int partition2(vector<T> &vec, int startIndex, int endIndex)
{
	T pivot = vec[startIndex];
	int left = startIndex;
	int right = endIndex;

	while ( left != right )
	{
		while (left < right && vec[right] > pivot)
			right--;
		while (left < right && vec[left] <= pivot)
			left++;
		if ( left < right ) 
		{
			using namespace std;
			swap(vec[left], vec[right]);
		}
	}

	vec[startIndex] = vec[left];
	vec[left] = pivot;
	return left;
}

//递归快排
template<typename T>
void quickSort1(vector<T> &vec, int startIndex, int endIndex)
{
	if (startIndex >= endIndex)
		return;

	int pivotIndex = partition1(vec, startIndex, endIndex);
	quickSort1(vec, startIndex, pivotIndex - 1);
	quickSort1(vec, pivotIndex + 1, endIndex);
}

//栈实现快排
template<typename T>
void quickSort2(vector<T> &vec, int startIndex, int endIndex)
{
	stack<map<string, int>> myStack;
	map<string, int> myMap;
	myMap.insert({ "startIndex", startIndex});
	myMap.insert({ "endIndex", endIndex });
	myStack.push(myMap);

	while ( !myStack.empty() )
	{
		map<string, int> paramMap = myStack.top();
		myStack.pop();
		int pivotIndex = partition2(vec, paramMap["startIndex"], paramMap["endIndex"]);
		if ( paramMap["startIndex"] < pivotIndex - 1 )
		{
			map<string, int> leftMap;
			leftMap.insert({ "startIndex", paramMap["startIndex"] });
			leftMap.insert({ "endIndex", pivotIndex - 1 });
			myStack.push(leftMap);
		}
		if (pivotIndex + 1 < paramMap["endIndex"])
		{
			map<string, int> rightMap;
			rightMap.insert({ "startIndex", pivotIndex + 1 });
			rightMap.insert({ "endIndex", paramMap["endIndex"] });
			myStack.push(rightMap);
		}
	}
}

void test01()
{
	vector<int> vec = {4, 4, 6, 5, 3, 2, 8, 1};
	//quickSort1(vec, 0, vec.size() - 1);
	quickSort2(vec, 0, vec.size() - 1);

	std::copy( vec.begin(), vec.end(), std::ostream_iterator<int>(std::cout, " "));
	cout << endl;
}

int main(int argc, char** argv)
{
	test01();


	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值