非递归实现快速排序算法

<pre name="code" class="cpp">//Data.h
#ifndef _DATA_H_
#define _DATA_H_
#include <IOSTREAM>
using namespace std;
template<class Type>
class Data
{
public:
	Data(Type* p, int low, int high);
	Data(const Data& data);
	Data()
	{

	}
	const Data operator=(const Data& data);
	friend ostream& operator<< <Type>(ostream& os, const Data<Type>& data);

	~Data()
	{
		
	}
	public:
	Type * arr;
	int m_low;
	int m_high;
};
#include "Data.cpp"
#endif //_DATA_H_

//Data.cpp
#ifndef _DATA_CPP_
#define _DATA_CPP_

#include "Data.h"
template<class Type>
const Data<Type> Data<Type>::operator=( const Data<Type>& data )
{
	arr = data.arr;
	m_low = data.m_low;
	m_high = data.m_high;
	return *this;
}

template<class Type>
Data<Type>::Data( const Data<Type>& data ) : arr(data.arr), m_low(data.m_low), m_high(data.m_high)
{
	
}

template<class Type>
Data<Type>::Data( Type* p, int low, int high ) :arr(p),m_low(low), m_high(high)
{
	
}

template<class Type>
ostream& operator << (ostream& os, const Data<Type>& data)
{
	for (int i = data.m_low; i <= data.m_high; ++i)
	{
		os << data.arr[i];
	}
	return os;
}

#endif //_DATA_CPP_


//show_main.cpp
#include <IOSTREAM>
#include "Data.h"
#include <stack>
using namespace std;

template <class Type>
int partition(Type arr[], int low, int high)
{
	Type x = arr[low];
	while (low<high)
	{
		while (low < high && arr[high]>=x)--high;
		arr[low] = arr[high];
		while (low < high && arr[low] <= x)++low;
		arr[high] = arr[low];
	}
	arr[low] = x;
	return low;
}

template <class Type>
void quickSort(Type arr[], int low, int high)
{
	if (low < high)
	{
		int pov = partition(arr, low, high);
		quickSort(arr, low, pov-1);
		quickSort(arr, pov+1, high);
	}
}

template<class Type>
void NonRecurQsort(Type arr[], int low, int high)
{
	stack<Data<Type> > s;
	if (!arr || low >= high)
		return ;
	int pov = 0;
	Data<Type> data(arr, low, high);
	s.push(data);
	Data<Type> temp;
	Data<Type> right, left;
	while (!s.empty())
	{
		temp = s.top();
		s.pop();
		pov = partition(temp.arr, temp.m_low, temp.m_high);
		//产生新的手头工作,如果满足条件,则放入
		right = Data<Type>(temp.arr, temp.m_low, pov-1);
		if (temp.m_low<pov-1)
			s.push(right);
		left = Data<Type>(temp.arr, pov+1, temp.m_high);
		if (pov+1 < temp.m_high)
			s.push(left);

	}

}

int main()
{
	int arr[10] = {2, 5, 8, 3, 0, 4, 9, 1, 7, 6};
//	NonRecurQsort<int>(arr, 0, 9); //success
	NonRecurQsort(arr, 0, 9);//success
	for (int i=0; i<10; i++)
		cout << arr[i] << " " ;
	cout << endl;
	return 0;
}



                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值