递归说到底,就是自己调用自己,是一种无穷迭代思维方式,简单粗暴的罗列。
递归对程序员的修养要求极高,无穷递归、栈溢出,各种问题,安全性比较难把握。
来段快排递归:
#include <iostream>
#include <windows.h>
using namespace std;
template<class T>
void quick_sort(T a[], int low, int high)
{
int first = low;
int last = high;
int key = a[first];
if(low >= high)
return;
while(first < last)
{
while(first < last && a[last] >= key)last--;
a[first] = a[last];
while(first < last && a[first] <= key)first++;
a[last] = a[first];
}
a[first] = key;
quick_sort(a, low, first - 1);
quick_sort(a, first + 1, high);
}
#define CONST_ARRAY_SIZE (3000)
int main()
{
SYSTEMTIME sys_time_start, sys_time_end;
int *pIntArray = (int*)malloc(CONST_ARRAY_SIZE*sizeof(int));
for(int i = 0; i < CONST_ARRAY_SIZE; i++)
pIntArray[i] = CONST_ARRAY_SIZE - i;
GetLocalTime(&sys_time_start);
quick_sort(pIntArray, 0, CONST_ARRAY_SIZE - 1);
GetLocalTime(&sys_time_end);
for(int j = 0; j < 10; j++)
cout<<pIntArray[j]<<" ";
cout<<endl;
cout<<"waste time = "<<(sys_time_end.wSecond - sys_time_start.wSecond)<<"s"<<(sys_time_end.wMilliseconds - sys_time_start.wMilliseconds)<<"ms"<<endl;
free(pIntArray);
return 0;
}
调整CONST_ARRAY_SIZE大小,快排迅速撑爆栈空间,造成runtime error!