非递归实现快速排序算法
2014-10-07 16:35
323 查看
<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; }
相关文章推荐
- 快速排序算法递归和非递归实现 [# 29]
- 快速排序算法的递归实现
- 快速排序算法递归与非递归实现
- 快速排序算法的递归实现的个人理解
- 【模板小程序】快速排序算法实现(递归+非递归)
- 快速排序算法的递归与非递归实现(C/C++)
- 《c程序设计语言》读书笔记-递归实现快速排序算法
- 《c程序设计语言》读书笔记-递归实现快速排序算法
- [置顶] 排序算法:快速排序算法实现及分析(递归形式和非递归形式)
- 一个C语言实现不含递归的高效快速排序算法
- C语言的快速排序算法代码-递归实现
- 快速排序算法原理及java递归实现
- 快速排序算法原理及java递归实现
- 二分查找算法递归实现&&快速排序算法实现
- 递归调用实现快速排序算法
- 快速排序算法原理及java递归实现
- 快速排序算法递归与非递归实现(二)【转】
- 快速排序算法原理及java递归实现
- 【算法】快速排序算法(递归实现 从小到大排列) 排序范围(0~n-1) n为数组元素个数
- 快速排序算法原理及java递归实现