stooge sort

:Introduction to Algorithms P95

T(n) = 3 * T(2*n/3) + O(1)

According to master method
T(n) = O(n^(log(2/3, 3) > O(n^2)

 

 

代码
///////////////////Test Code/////////////////////////
#include "stdafx.h"
#include
"stdlib.h"
#include
<time.h>
#include
"basic_algorithm.h"
#include
<iostream>
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{

srand((unsigned)time(NULL));
int *arr = new int[20];
for(int i = 0; i < 20; ++i)
{
arr[i]
= rand() % 30;
}
enzo::stooge_sort(arr,
20);
for(int i = 0; i < 20; ++i)
{
cout
<< arr[i] << " ";
}
cout
<< endl;
system(
"pause");
return 0;
}

///////////////////Source Code///////////////////////
template<typename _T>
void stooge_sort(_T *arr, int n)
{
stooge_sort(arr,
0, n-1);
}

template
<typename _T>
void stooge_sort(_T *arr, int from, int to)
{
if(arr[to] < arr[from])
{
ez_swap(arr[to], arr[from]);
}
if(from + 1 < to)
{
int k = (to - from + 1) / 3;
stooge_sort(arr, from, to
- k);
stooge_sort(arr, from
+ k, to);
stooge_sort(arr, from, to
- k);
}
}

 

posted @ 2010-04-29 21:31  Yang Enzo  阅读(220)  评论(0编辑  收藏  举报