//end 是超尾/*插入排序
最好时间复杂度O(n),最坏时间复杂度O(n^2),随机序列的复杂度接近后者。*/template <class BidirectionalIterator>
//因为需要迭代器的有(++、--、=、!=)这几个功能,所以需要BinaryIterator这种concept
void insertionsort(BidirectionalIterator begin, BidirectionalIterator end)
{
BidirectionalIterator p, q;
typedef typename iterator_traits<BidirectionalIterator>::value_type value_type; //迭代器所指的对象的型别
value_type tmp;
begin++;
p=begin;
begin--;
for(; p!=end; p++)
{
tmp = *p;
for(q=p; q!=begin && tmp<*(q-1); q--)
*q = *(q-1);
*q = tmp;
}
}/*选择排序
最好最坏复杂度都是O(n^2),优点是移动次数较少*/template <class BidirectionalIterator> //同上
void selectionsort(BidirectionalIterator begin,BidirectionalIterator end)
{
BidirectionalIterator p, q, least;
end--;
BidirectionalIterator end_It=end;
end++;
for(p=begin; p!=end_It; p++)
{
for(q=p+1,least=p; q!=end; q++)
if(*q < *least)
least = q;
if(p != least)
swap(*p, *least);
}
}/*冒泡排序
时间复杂度是O(n^2),缺点是移动次数较多,认为是三种基本排序中最差的。*/template <class BidirectionalIterator>
void bubblesort(BidirectionalIterator begin, BidirectionalIterator end)
{
BidirectionalIterator p, q;
end--;
for(p=begin; p!=end; p++)
for(q=end; q>p; q--)
if(*q < *(q-1))
swap(*q, *(q-1));
}
[此贴子已经被作者于2006-10-9 14:16:26编辑过]
template<class RandomAccessIterator,class Distance>
void movedown(RandomAccessIterator data, Distance first,Distance last)
{
Distance largest = 2*first + 1;
while(largest <= last)
{
if( largest<last && (*(data+largest)<*(data+largest+1)) ) //--
largest++;
if(*(data+first)<*(data+largest)) //--
{
swap(*(data+first), *(data+largest)); //--
first = largest;
largest = largest*2 + 1;
}
else
break;
}
}
template<class RandomAccessIterator>
void heapsort(RandomAccessIterator begin,RandomAccessIterator end)
{
typedef typename iterator_traits<RandomAccessIterator>::distance_type distance_type;
distance_type size = end - begin;
for(distance_type i=size/2-1; i>=0; i--)
movedown(begin, i, size-1);
for(distance_type j=size-1; j>0; j--)
{
swap(*begin, *(begin+j)); //--
movedown(begin, 0, j-1);
}
}
[此贴子已经被作者于2006-10-9 17:02:35编辑过]