函数模板实现快排

xiaoxiao2021-02-28  72

函数模板可以用来创建一个通用的函数,以支持多种不同的形参,避免重载函数的函数体重复设计。它的最大特点是把函数使用的数据类型作为参数。 函数模板的声明形式为:

template<类型形式参数表> 返回类型 函数名(形式参数表) { ... 函数体 }

实现快排形式①(从小到大排)

template <class T> void Quicksort(T *a,int left,int right) { int i,j,t; T temp; if(left>right) return; temp = a[left]; i = left; j = right; while(i!=j) { while(a[j]>=temp && i<j) j--; while(a[i]<=temp && i<j) i++; if(i<j) { t = a[i]; a[i] = a[j]; a[j] = t; } } a[left] = a[i]; a[i] = temp; quicksort(a,left,i-1); quicksort(a,i+1,right); }

实现形式②(从小到大排)

template<class type> void Myswap (type& a, type& b) { type c = a; a = b; b = c; } template<class iterator> void Quicksort (iterator begin, iterator end) { iterator l = begin; iterator r = end; r--; for (iterator i = begin, j = r; i != j;) { while (! (i == l || *l < *i)) i++; if (i != l) { MySwap (*l, *i); l = i; } while (! (j == l || *j < *l)) j--; if (j != l) { MySwap (*l, *j); l = j; } } iterator it = begin; it++; if (l != begin && l != it) quicksort (begin, l); it = l; it++; if (it != end && it != r) quicksort (it, end); }
转载请注明原文地址: https://www.6miu.com/read-60103.html

最新回复(0)