用C++编程 排序(冒泡,选择,快速)用函数实现 还要统计出排序次数
谢谢拉!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
[此贴子已经被作者于2007-6-27 17:43:23编辑过]
1. you may want to digest apib2007's posts.
2. for quicksort I want to give some comments: the pivot is critical to the average running time O(n lgn). A bad pivot could give you the worst-case running time--- O(n^2). I described my random quicksort below;
3. a better approach is the so-called median of the three pivot technique. Just google for it.
----------------------------------------------------------------------------------------------
/**
p --- left index
r --- right index
both p and r are inclusive.
*/
int partition(int *a, int p, int r)
{
int x = a[r];
int i = p - 1;
for(int j=p; j<r; ++j)
{
if(a[j] <= x )
{
++i;
swap(a[i], a[j]);
}
}
++i;
swap(a[i], a[r]);
return i;
}
int partition_random(int *a, int p, int r)
{
// randomly return an index between p and r, both inclusive
int i = random(p, r);
swap(a[i], a[r]);
return partition(a, p, r);
}
void quicksort(int *a, int p, int r)
{
if( p < r)
{
/**
You could do a normal partition, but a random
partition is guarantteed to give you better
average running time. In this case, the running
time is O(n lgn).
*/
//int q = partition(a, p, r);
int q = partition_random(a, p, r);
quicksort(a, p, q-1);
quicksort(a, q+1, r);
}
}
// my simple pseudo-random number generator.
// This is a bad one, you can find good ones in
// boost library at www.boost.org.
int random(int p, int r)
{
return p+( rand() | (rand() << 16) )% (r-p+1);
}