SGI STL: list::sort()算法

来源:互联网 发布:mac系统虚拟机安装win7 编辑:程序博客网 时间:2024/06/05 17:36

文章来源: http://dzbjet.spaces.live.com/blog/cns!b69ae5707b3539f!116.entry


源码:
// list 不能使用STL 算法 sort(),必须使用自己的 sort() member function,
// 因为STL算法sort() 只接受RamdonAccessIterator.
// 本函式采用 quick sort.
template <class T, class Alloc>
void list<T, Alloc>::sort() {
  // 以下判断,如果是空白串行,或仅有一个元素,就不做任何动作。
  // 使用 size() == 0 || size() == 1 来判断,虽然也可以,但是比较慢。
  if (node->next == node || link_type(node->next)->next == node) return;

  // 一些新的 lists,做为中介数据存放区
  list<T, Alloc> carry;
  list<T, Alloc> counter[64];
  int fill = 0;
  while (!empty()) {
    carry.splice(carry.begin(), *this, begin());
    int i = 0;
    while(i < fill && !counter[i].empty()) {
      counter[i].merge(carry);
      carry.swap(counter[i++]);
    }
    carry.swap(counter[i]);         
    if (i == fill) ++fill;
  }

  for (int i = 1; i < fill; ++i)
     counter[i].merge(counter[i-1]);
  swap(counter[fill-1]);
}

 

回答一:

http://www.programfan.com/club/showtxt.asp?id=138066

是归并排序。
counter[i]存的是2^i个元素组成的链表。
carry存的链表依次与counter[i]合并组成2^(i+1)元素的链表保存到counter[i+1]去

回答二:

SGI STL: list::sort算法

        非递归的快速排序算法,实现得很巧妙。
        写了一个验证思路的:
       
#include <iostream>
#include <math.h>

using namespace std;

void qsort(int array[], size_t size)
{
        // 3^0, 3^1, 3^2, 3^3, 3^4, 3^5, 3^6, 3^7, 3^8, 3^9; for convenience, counter[0] not used.
        list<int> counter[10];
        int index = 0;
        while( index < size )
        {
                int v = array[index];

                int i = 1;
                list<int> temp; temp.push_back(v);
                counter[i].merge(temp);


                if( counter[i].size() % 3 == 0 && counter[i].size() / 3 == i )
                {
                        // need to up to the next level
                        int j = i + 1;
                        do {
                                counter[j].merge(counter[j-1]);
                        } while ( counter[j].size() > pow(3,j++) );
                }
                ++index;
        }

        for( int k = 1; k < 10; ++k )
        {
                counter[k].merge(counter[k-1]);
        }

        copy(counter[k-1].begin(), counter[k-1].end(), ostream_iterator<int>(cout, " "));
}


int main(int argc, char* argv[])
{
        int array[] = { 1, 5, 8, 3, 2, 9, 4, 41, 32, 0, 7, 6, 37};
        qsort(array, sizeof(array)/sizeof(array[0]));
        return 0;
}
 
我认为是归并..呵呵.实现的确很巧妙.
闻香止步 淘宝 木雕