zoukankan      html  css  js  c++  java
  • 浅析SkipList跳跃表原理及代码实现

     

     

    转载请注明:http://blog.csdn.net/ict2014/article/details/17394259

    SkipList在leveldb以及lucence中都广为使用,是比较高效的数据结构。由于它的代码以及原理实现的简单性,更为人们所接受。我们首先看看SkipList的定义,为什么叫跳跃表?

    “     Skip lists  are data structures  that use probabilistic  balancing rather  than  strictly  enforced balancing. As a result, the algorithms  for insertion  and deletion in skip lists  are much simpler and significantly  faster  than  equivalent  algorithms  for balanced trees.   ”

    译文:跳跃表使用概率均衡技术而不是使用强制性均衡,因此,对于插入和删除结点比传统上的平衡树算法更为简洁高效。 

    我们看一个图就能明白,什么是跳跃表,如图1所示:

                                                                     图1:跳跃表简单示例

    如上图所示,是一个即为简单的跳跃表。传统意义的单链表是一个线性结构,向有序的链表中插入一个节点需要O(n)的时间,查找操作需要O(n)的时间。如果我们使用图1所示的跳跃表,就可以减少查找所需时间为O(n/2),因为我们可以先通过每个节点的最上面的指针先进行查找,这样子就能跳过一半的节点。比如我们想查找19,首先和6比较,大于6之后,在和9进行比较,然后在和12进行比较......最后比较到21的时候,发现21大于19,说明查找的点在17和21之间,从这个过程中,我们可以看出,查找的时候跳过了3、7、12等点,因此查找的复杂度为O(n/2)。查找的过程如下图2:

                                                                      图2:跳跃表查找操作简单示例

    其实,上面基本上就是跳跃表的思想,每一个结点不单单只包含指向下一个结点的指针,可能包含很多个指向后续结点的指针,这样就可以跳过一些不必要的结点,从而加快查找、删除等操作。对于一个链表内每一个结点包含多少个指向后续元素的指针,这个过程是通过一个随机函数生成器得到,这样子就构成了一个跳跃表。这就是为什么论文“Skip Lists : A Probabilistic Alternative to Balanced Trees ”中有“概率”的原因了,就是通过随机生成一个结点中指向后续结点的指针数目。随机生成的跳跃表可能如下图3所示:

                                                                     图3:随机生成的跳跃表

    跳跃表的大体原理,我们就讲述到这里。下面我们将从如下几个方面来探讨跳跃表的操作:

    1、重要数据结构定义

    2、初始化表

    3、查找

    4、插入

    5、删除

    6、随机数生成器

    7、释放表

    8、性能比较

    (一)重要数据结构定义

          从图3中,我们可以看出一个跳跃表是由结点组成,结点之间通过指针进行链接。因此我们定义如下数据结构:

    [cpp] view plain copy
     
    1. //定义key和value的类型  
    2. typedef int KeyType;  
    3. typedef int ValueType;  
    4.       
    5. //定义结点  
    6. typedef struct nodeStructure* Node;  
    7. struct nodeStructure{  
    8.     KeyType key;  
    9.     ValueType value;  
    10.     Node forward[1];  
    11. };  
    12.       
    13. //定义跳跃表  
    14. typedef struct listStructure* List;  
    15. struct listStructure{  
    16.     int level;  
    17.     Node header;  
    18. };  
    每一个结点都由3部分组成,key(关键字)、value(存放的值)以及forward数组(指向后续结点的数组,这里只保存了首地址)。通过这些结点,我们就可以创建跳跃表List,它是由两个元素构成,首结点以及level(当前跳跃表内最大的层数或者高度)。这样子,基本的数据结构定义完毕了。

    (二)初始化表
         初始化表主要包括两个方面,首先就是header节点和NIL结点的申请,其次就是List资源的申请。

    [cpp] view plain copy
     
    1. void SkipList::NewList(){  
    2.     //设置NIL结点  
    3.     NewNodeWithLevel(0, NIL_);  
    4.     NIL_->key = 0x7fffffff;  
    5.     //设置链表List  
    6.     list_ = (List)malloc(sizeof(listStructure));  
    7.     list_->level = 0;  
    8.     //设置头结点  
    9.     NewNodeWithLevel(MAX_LEVEL,list_->header);  
    10.     for(int i = 0; i < MAX_LEVEL; ++i){  
    11.         list_->header->forward[i] = NIL_;  
    12.     }  
    13.     //设置链表元素的数目  
    14.     size_ = 0;  
    15. }  
    16.   
    17. void SkipList::NewNodeWithLevel(const int& level,  
    18.                                 Node& node){  
    19.     //新结点空间大小  
    20.     int total_size = sizeof(nodeStructure) + level*sizeof(Node);  
    21.     //申请空间  
    22.     node = (Node)malloc(total_size);  
    23.     assert(node != NULL);  
    24. }  

    其中,NewNodeWithLevel是申请结点(总共level层)所需的内存空间。NIL_节点会在后续全部代码实现中可以看到。

    (三)查找

        查找就是给定一个key,查找这个key是否出现在跳跃表中,如果出现,则返回其值,如果不存在,则返回不存在。我们结合一个图就是讲解查找操作,如下图4所示:

                                                           图4:查找操作前的跳跃表

    如果我们想查找19是否存在?如何查找呢?我们从头结点开始,首先和9进行判断,此时大于9,然后和21进行判断,小于21,此时这个值肯定在9结点和21结点之间,此时,我们和17进行判断,大于17,然后和21进行判断,小于21,此时肯定在17结点和21结点之间,此时和19进行判断,找到了。具体的示意图如图5所示:

                                                            图5:查找操作后的跳跃表

    [cpp] view plain copy
     
    1. bool SkipList::Search(const KeyType& key,  
    2.                       ValueType& value){  
    3.     Node x = list_->header;  
    4.     int i;  
    5.     for(i = list_->level; i >= 0; --i){  
    6.         while(x->forward[i]->key < key){  
    7.             x = x->forward[i];  
    8.         }  
    9.     }  
    10.     x = x->forward[0];  
    11.     if(x->key == key){  
    12.         value = x->value;  
    13.         return true;  
    14.     }else{  
    15.         return false;  
    16.     }  
    17. }  

    (四)插入

          插入包含如下几个操作:1、查找到需要插入的位置   2、申请新的结点    3、调整指针。

    我们结合下图6进行讲解,查找如下图的灰色的线所示  申请新的结点如17结点所示, 调整指向新结点17的指针以及17结点指向后续结点的指针。这里有一个小技巧,就是使用update数组保存大于17结点的位置,这样如果插入17结点的话,就指针调整update数组和17结点的指针、17结点和update数组指向的结点的指针。update数组的内容如红线所示,这些位置才是有可能更新指针的位置。

       

                                                        图6:插入操作示意图(感谢博主:来自cnblogs的qiang.xu )

    [cpp] view plain copy
     
    1. bool SkipList::Insert(const KeyType& key,  
    2.                       const ValueType& value){  
    3.     Node update[MAX_LEVEL];  
    4.     int i;  
    5.     Node x = list_->header;  
    6.     //寻找key所要插入的位置  
    7.     //保存大于key的位置信息  
    8.     for(i = list_->level; i >= 0; --i){  
    9.         while(x->forward[i]->key < key){  
    10.             x = x->forward[i];  
    11.         }  
    12.   
    13.         update[i] = x;  
    14.     }  
    15.   
    16.     x = x->forward[0];  
    17.     //如果key已经存在  
    18.     if(x->key == key){  
    19.         x->value = value;  
    20.         return false;  
    21.     }else{  
    22.         //随机生成新结点的层数  
    23.         int level = RandomLevel();  
    24.         //为了节省空间,采用比当前最大层数加1的策略  
    25.         if(level > list_->level){  
    26.             level = ++list_->level;  
    27.             update[level] = list_->header;  
    28.         }  
    29.         //申请新的结点  
    30.         Node newNode;  
    31.         NewNodeWithLevel(level, newNode);  
    32.         newNode->key = key;  
    33.         newNode->value = value;  
    34.   
    35.         //调整forward指针  
    36.         for(int i = level; i >= 0; --i){  
    37.             x = update[i];  
    38.             newNode->forward[i] = x->forward[i];  
    39.             x->forward[i] = newNode;  
    40.         }  
    41.           
    42.         //更新元素数目  
    43.         ++size_;  
    44.   
    45.         return true;  
    46.     }  
    47. }  

    (五)删除

        删除操作类似于插入操作,包含如下3步:1、查找到需要删除的结点 2、删除结点  3、调整指针

                                                                                 图7:删除操作示意图(感谢博主qiang.xu 来自cnblogs)

    [cpp] view plain copy
     
    1. bool SkipList::Delete(const KeyType& key,  
    2.                       ValueType& value){  
    3.     Node update[MAX_LEVEL];  
    4.     int i;  
    5.     Node x = list_->header;  
    6.     //寻找要删除的结点  
    7.     for(i = list_->level; i >= 0; --i){  
    8.         while(x->forward[i]->key < key){  
    9.             x = x->forward[i];  
    10.         }  
    11.   
    12.         update[i] = x;  
    13.     }  
    14.   
    15.     x = x->forward[0];  
    16.     //结点不存在  
    17.     if(x->key != key){  
    18.         return false;  
    19.     }else{  
    20.         value = x->value;  
    21.         //调整指针  
    22.         for(i = 0; i <= list_->level; ++i){  
    23.             if(update[i]->forward[i] != x)  
    24.                 break;  
    25.             update[i]->forward[i] = x->forward[i];  
    26.         }  
    27.         //删除结点  
    28.         free(x);  
    29.         //更新level的值,有可能会变化,造成空间的浪费  
    30.         while(list_->level > 0  
    31.             && list_->header->forward[list_->level] == NIL_){  
    32.             --list_->level;  
    33.         }  
    34.           
    35.         //更新链表元素数目  
    36.         --size_;  
    37.   
    38.         return true;  
    39.     }  
    40. }  

    (六)随机数生成器

          再向跳跃表中插入新的结点时候,我们需要生成该结点的层数,使用的就是随机数生成器,随机的生成一个层数。这部分严格意义上讲,不属于跳跃表的一部分。随机数生成器说简单很简单,说难很也很难,看你究竟是否想生成随机的数。可以采用c语言中srand以及rand函数,也可以自己设计随机数生成器。

          此部分我们采用levelDB随机数生成器:

    [cpp] view plain copy
     
    1. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.  
    2. // Use of this source code is governed by a BSD-style license that can be  
    3. // found in the LICENSE file. See the AUTHORS file for names of contributors.  
    4.   
    5.   
    6. #include <stdint.h>  
    7.   
    8. //typedef unsigned int           uint32_t;  
    9. //typedef unsigned long long     uint64_t;  
    10.   
    11. // A very simple random number generator.  Not especially good at  
    12. // generating truly random bits, but good enough for our needs in this  
    13. // package.  
    14. class Random {  
    15.  private:  
    16.   uint32_t seed_;  
    17.  public:  
    18.   explicit Random(uint32_t s) : seed_(s & 0x7fffffffu) {  
    19.     // Avoid bad seeds.  
    20.     if (seed_ == 0 || seed_ == 2147483647L) {  
    21.       seed_ = 1;  
    22.     }  
    23.   }  
    24.   uint32_t Next() {  
    25.     static const uint32_t M = 2147483647L;   // 2^31-1  
    26.     static const uint64_t A = 16807;  // bits 14, 8, 7, 5, 2, 1, 0  
    27.     // We are computing  
    28.     //       seed_ = (seed_ * A) % M,    where M = 2^31-1  
    29.     //  
    30.     // seed_ must not be zero or M, or else all subsequent computed values  
    31.     // will be zero or M respectively.  For all other values, seed_ will end  
    32.     // up cycling through every number in [1,M-1]  
    33.     uint64_t product = seed_ * A;  
    34.   
    35.     // Compute (product % M) using the fact that ((x << 31) % M) == x.  
    36.     seed_ = static_cast<uint32_t>((product >> 31) + (product & M));  
    37.     // The first reduction may overflow by 1 bit, so we may need to  
    38.     // repeat.  mod == M is not possible; using > allows the faster  
    39.     // sign-bit-based test.  
    40.     if (seed_ > M) {  
    41.       seed_ -= M;  
    42.     }  
    43.     return seed_;  
    44.   }  
    45.   // Returns a uniformly distributed value in the range [0..n-1]  
    46.   // REQUIRES: n > 0  
    47.   uint32_t Uniform(int n) { return (Next() % n); }  
    48.   
    49.   // Randomly returns true ~"1/n" of the time, and false otherwise.  
    50.   // REQUIRES: n > 0  
    51.   bool OneIn(int n) { return (Next() % n) == 0; }  
    52.   
    53.   // Skewed: pick "base" uniformly from range [0,max_log] and then  
    54.   // return "base" random bits.  The effect is to pick a number in the  
    55.   // range [0,2^max_log-1] with exponential bias towards smaller numbers.  
    56.   uint32_t Skewed(int max_log) {  
    57.     return Uniform(1 << Uniform(max_log + 1));  
    58.   }  
    59. };  

    其中核心的是 seed_ = (seed_ * A) % M这个函数,并且调用一次就重新更新一个种子seed。以达到随机性。

    根据个人喜好,自己可以独立设计随机数生成器,只要能够返回一个随机的数字即可。

    (七)释放表

          释放表的操作比较简单,只要像单链表一样释放表就可以,释放表的示意图8如下:

                                                                          图8:释放表

    [cpp] view plain copy
     
    1. void SkipList::FreeList(){  
    2.     Node p = list_->header;  
    3.     Node q;  
    4.     while(p != NIL_){  
    5.         q = p->forward[0];  
    6.         free(p);  
    7.         p = q;  
    8.     }  
    9.     free(p);  
    10.     free(list_);  
    11. }  

    (八)性能比较

      我们对跳跃表、平衡树等进行比较,如下图9所示:

                                                                                  图9:性能比较图

    从中可以看出,随机跳跃表表现性能很不错,节省了大量复杂的调节平衡树的代码。

    ========自己开发的源代码,部分参照qiang.xu====================

    下面我将自己用C++实现的代码贴出来,总共包含了如下几个文件:

    1、Main.cpp 主要用于测试SkipList

    2、skiplist.h  接口声明以及重要数据结构定义

    3、skiplist.cpp 接口的具体实现

    4、random.h  随机数生成器

    --------------------------------------Main.cpp----------------------------------------------------

    [cpp] view plain copy
     
    1. //此文件用于测试skiplist  
    2. //  
    3. //@作者:张海波  
    4. //@时间:2013-12-17  
    5. //@版权:个人所有  
    6.   
    7. #include "skiplist.h"  
    8. #include <iostream>  
    9.   
    10. using namespace std;  
    11.   
    12. int main(int argc, char** argv)  
    13. {  
    14.     cout << "test is starting ....." << endl;  
    15.   
    16.     SkipList list;  
    17.   
    18.     //测试插入  
    19.     for(int i = 0; i < 100; ++i){  
    20.         list.Insert(i, i+10);  
    21.         //cout << list.GetCurrentLevel() << endl;  
    22.     }  
    23.     cout << "The number of elements in SkipList is :"   
    24.          << list.size()   
    25.          << endl;  
    26.     if(list.size() != 100){  
    27.         cout << "Insert failure." << endl;  
    28.     }else{  
    29.         cout << "Insert success." << endl;  
    30.     }  
    31.       
    32.     //测试查找  
    33.     bool is_search_success = true;  
    34.     for(int i = 0; i < 100; ++i){  
    35.         int value;  
    36.         if(!(list.Search(i,value) && (value == i+10))){  
    37.             is_search_success = false;  
    38.             break;  
    39.         }  
    40.     }  
    41.     if(is_search_success){  
    42.         cout << "Search success." << endl;  
    43.     }else{  
    44.         cout << "Search failure." << endl;  
    45.     }  
    46.       
    47.     //测试删除  
    48.     bool is_delete_success = true;  
    49.     for(int i = 0; i < 100; ++i){  
    50.         int value;  
    51.         if(!(list.Delete(i,value) && (value == i+10))){  
    52.             is_delete_success = false;  
    53.             break;  
    54.         }  
    55.     }  
    56.     if(is_delete_success){  
    57.         cout << "Delete success." << endl;  
    58.     }else{  
    59.         cout << "Delete failure." << endl;  
    60.     }  
    61.       
    62.     cout << "test is finished ...." << endl;  
    63.     return 0;  
    64. }  

    --------------------------------------------------skiplist.h---------------------------------------------------
    [cpp] view plain copy
     
    1. //跳表实现  
    2. //  
    3. //参考文章为:Skip lists: a probabilistic alternative to balanced trees  
    4. //  
    5. //提供如下接口:  
    6. //   Search:搜索给定key的值  
    7. //   Insert:插入指定的key及value  
    8. //   Delete:删除指定的key  
    9. //  
    10. //@作者: 张海波  
    11. //@时间: 2013-12-17  
    12. //@版权: 个人所有  
    13. //  
    14.   
    15. #include <stddef.h>  
    16. #include "random.h"  
    17.   
    18. //定义调试开关  
    19. #define Debug  
    20.   
    21. //最大层数  
    22. const int MAX_LEVEL = 16;  
    23.   
    24. //定义key和value的类型  
    25. typedef int KeyType;  
    26. typedef int ValueType;  
    27.       
    28. //定义结点  
    29. typedef struct nodeStructure* Node;  
    30. struct nodeStructure{  
    31.     KeyType key;  
    32.     ValueType value;  
    33.     Node forward[1];  
    34. };  
    35.       
    36. //定义跳跃表  
    37. typedef struct listStructure* List;  
    38. struct listStructure{  
    39.     int level;  
    40.     Node header;  
    41. };  
    42.   
    43. class SkipList{  
    44. public:  
    45.     //初始化表结构  
    46.     SkipList():rnd_(0xdeadbeef)  
    47.     { NewList(); }  
    48.       
    49.     //释放内存空间  
    50.     ~SkipList(){ FreeList(); }  
    51.   
    52.     //搜索key,保存结果至value  
    53.     //找到,返回true  
    54.     //未找到,返回false  
    55.     bool Search(const KeyType& key,  
    56.                 ValueType& value);  
    57.   
    58.     //插入key和value  
    59.     bool Insert(const KeyType& key,  
    60.                 const ValueType& value);  
    61.   
    62.     //删除key,保存结果至value  
    63.     //删除成功返回true  
    64.     //未删除成功返回false  
    65.     bool Delete(const KeyType& key,  
    66.                 ValueType& value);  
    67.   
    68.     //链表包含元素的数目  
    69.     int size(){ return size_; }  
    70.   
    71.     //打印当前最大的level  
    72.     int GetCurrentLevel();  
    73. private:  
    74.     //初始化表  
    75.     void NewList();  
    76.   
    77.     //释放表  
    78.     void FreeList();  
    79.       
    80.     //创建一个新的结点,结点的层数为level  
    81.     void NewNodeWithLevel(const int& level,  
    82.                           Node& node);  
    83.   
    84.     //随机生成一个level  
    85.     int RandomLevel();  
    86. private:          
    87.     List list_;  
    88.     Node NIL_;  
    89.     //链表中包含元素的数目  
    90.     size_t size_;  
    91.     //随机器生成器  
    92.     Random rnd_;  
    93. };  

    -------------------------------------------------------------skiplist.cpp-----------------------------------------------------
    [cpp] view plain copy
     
    1. //skiplist头文件重要函数实现  
    2. //  
    3. //@作者:张海波  
    4. //@时间:2013-12-17  
    5. //@版权:个人所有  
    6.   
    7. #include "skiplist.h"  
    8. #include "time.h"  
    9. #include <assert.h>  
    10. #include <stdlib.h>  
    11. #include <string>  
    12. #include <iostream>  
    13.   
    14. using namespace std;  
    15.   
    16. void DebugOutput(const string& information){  
    17. #ifdef Debug  
    18.     cout << information << endl;  
    19. #endif  
    20. }  
    21.   
    22. void SkipList::NewList(){  
    23.     //设置NIL结点  
    24.     NewNodeWithLevel(0, NIL_);  
    25.     NIL_->key = 0x7fffffff;  
    26.     //设置链表List  
    27.     list_ = (List)malloc(sizeof(listStructure));  
    28.     list_->level = 0;  
    29.     //设置头结点  
    30.     NewNodeWithLevel(MAX_LEVEL,list_->header);  
    31.     for(int i = 0; i < MAX_LEVEL; ++i){  
    32.         list_->header->forward[i] = NIL_;  
    33.     }  
    34.     //设置链表元素的数目  
    35.     size_ = 0;  
    36. }  
    37.   
    38. void SkipList::NewNodeWithLevel(const int& level,  
    39.                                 Node& node){  
    40.     //新结点空间大小  
    41.     int total_size = sizeof(nodeStructure) + level*sizeof(Node);  
    42.     //申请空间  
    43.     node = (Node)malloc(total_size);  
    44.     assert(node != NULL);  
    45. }  
    46.   
    47. void SkipList::FreeList(){  
    48.     Node p = list_->header;  
    49.     Node q;  
    50.     while(p != NIL_){  
    51.         q = p->forward[0];  
    52.         free(p);  
    53.         p = q;  
    54.     }  
    55.     free(p);  
    56.     free(list_);  
    57. }  
    58.   
    59.   
    60. bool SkipList::Search(const KeyType& key,  
    61.                       ValueType& value){  
    62.     Node x = list_->header;  
    63.     int i;  
    64.     for(i = list_->level; i >= 0; --i){  
    65.         while(x->forward[i]->key < key){  
    66.             x = x->forward[i];  
    67.         }  
    68.     }  
    69.     x = x->forward[0];  
    70.     if(x->key == key){  
    71.         value = x->value;  
    72.         return true;  
    73.     }else{  
    74.         return false;  
    75.     }  
    76. }  
    77.   
    78.   
    79. bool SkipList::Insert(const KeyType& key,  
    80.                       const ValueType& value){  
    81.     Node update[MAX_LEVEL];  
    82.     int i;  
    83.     Node x = list_->header;  
    84.     //寻找key所要插入的位置  
    85.     //保存大约key的位置信息  
    86.     for(i = list_->level; i >= 0; --i){  
    87.         while(x->forward[i]->key < key){  
    88.             x = x->forward[i];  
    89.         }  
    90.   
    91.         update[i] = x;  
    92.     }  
    93.   
    94.     x = x->forward[0];  
    95.     //如果key已经存在  
    96.     if(x->key == key){  
    97.         x->value = value;  
    98.         return false;  
    99.     }else{  
    100.         //随机生成新结点的层数  
    101.         int level = RandomLevel();  
    102.         //为了节省空间,采用比当前最大层数加1的策略  
    103.         if(level > list_->level){  
    104.             level = ++list_->level;  
    105.             update[level] = list_->header;  
    106.         }  
    107.         //申请新的结点  
    108.         Node newNode;  
    109.         NewNodeWithLevel(level, newNode);  
    110.         newNode->key = key;  
    111.         newNode->value = value;  
    112.   
    113.         //调整forward指针  
    114.         for(int i = level; i >= 0; --i){  
    115.             x = update[i];  
    116.             newNode->forward[i] = x->forward[i];  
    117.             x->forward[i] = newNode;  
    118.         }  
    119.           
    120.         //更新元素数目  
    121.         ++size_;  
    122.   
    123.         return true;  
    124.     }  
    125. }  
    126.   
    127.   
    128. bool SkipList::Delete(const KeyType& key,  
    129.                       ValueType& value){  
    130.     Node update[MAX_LEVEL];  
    131.     int i;  
    132.     Node x = list_->header;  
    133.     //寻找要删除的结点  
    134.     for(i = list_->level; i >= 0; --i){  
    135.         while(x->forward[i]->key < key){  
    136.             x = x->forward[i];  
    137.         }  
    138.   
    139.         update[i] = x;  
    140.     }  
    141.   
    142.     x = x->forward[0];  
    143.     //结点不存在  
    144.     if(x->key != key){  
    145.         return false;  
    146.     }else{  
    147.         value = x->value;  
    148.         //调整指针  
    149.         for(i = 0; i <= list_->level; ++i){  
    150.             if(update[i]->forward[i] != x)  
    151.                 break;  
    152.             update[i]->forward[i] = x->forward[i];  
    153.         }  
    154.         //删除结点  
    155.         free(x);  
    156.         //更新level的值,有可能会变化,造成空间的浪费  
    157.         while(list_->level > 0  
    158.             && list_->header->forward[list_->level] == NIL_){  
    159.             --list_->level;  
    160.         }  
    161.           
    162.         //更新链表元素数目  
    163.         --size_;  
    164.   
    165.         return true;  
    166.     }  
    167. }  
    168.   
    169.   
    170. int SkipList::RandomLevel(){     
    171.     int level = static_cast<int>(rnd_.Uniform(MAX_LEVEL));  
    172.     if(level == 0){  
    173.         level = 1;  
    174.     }  
    175.     //cout << level << endl;  
    176.     return level;  
    177. }  
    178.   
    179. int SkipList::GetCurrentLevel(){  
    180.     return list_->level;  
    181. }  

    -----------------------------------------------------------random.h-------------------------------------------------------
    [cpp] view plain copy
     
    1. // Copyright (c) 2011 The LevelDB Authors. All rights reserved.  
    2. // Use of this source code is governed by a BSD-style license that can be  
    3. // found in the LICENSE file. See the AUTHORS file for names of contributors.  
    4.   
    5.   
    6. #include <stdint.h>  
    7.   
    8. //typedef unsigned int           uint32_t;  
    9. //typedef unsigned long long     uint64_t;  
    10.   
    11. // A very simple random number generator.  Not especially good at  
    12. // generating truly random bits, but good enough for our needs in this  
    13. // package.  
    14. class Random {  
    15.  private:  
    16.   uint32_t seed_;  
    17.  public:  
    18.   explicit Random(uint32_t s) : seed_(s & 0x7fffffffu) {  
    19.     // Avoid bad seeds.  
    20.     if (seed_ == 0 || seed_ == 2147483647L) {  
    21.       seed_ = 1;  
    22.     }  
    23.   }  
    24.   uint32_t Next() {  
    25.     static const uint32_t M = 2147483647L;   // 2^31-1  
    26.     static const uint64_t A = 16807;  // bits 14, 8, 7, 5, 2, 1, 0  
    27.     // We are computing  
    28.     //       seed_ = (seed_ * A) % M,    where M = 2^31-1  
    29.     //  
    30.     // seed_ must not be zero or M, or else all subsequent computed values  
    31.     // will be zero or M respectively.  For all other values, seed_ will end  
    32.     // up cycling through every number in [1,M-1]  
    33.     uint64_t product = seed_ * A;  
    34.   
    35.     // Compute (product % M) using the fact that ((x << 31) % M) == x.  
    36.     seed_ = static_cast<uint32_t>((product >> 31) + (product & M));  
    37.     // The first reduction may overflow by 1 bit, so we may need to  
    38.     // repeat.  mod == M is not possible; using > allows the faster  
    39.     // sign-bit-based test.  
    40.     if (seed_ > M) {  
    41.       seed_ -= M;  
    42.     }  
    43.     return seed_;  
    44.   }  
    45.   // Returns a uniformly distributed value in the range [0..n-1]  
    46.   // REQUIRES: n > 0  
    47.   uint32_t Uniform(int n) { return (Next() % n); }  
    48.   
    49.   // Randomly returns true ~"1/n" of the time, and false otherwise.  
    50.   // REQUIRES: n > 0  
    51.   bool OneIn(int n) { return (Next() % n) == 0; }  
    52.   
    53.   // Skewed: pick "base" uniformly from range [0,max_log] and then  
    54.   // return "base" random bits.  The effect is to pick a number in the  
    55.   // range [0,2^max_log-1] with exponential bias towards smaller numbers.  
    56.   uint32_t Skewed(int max_log) {  
    57.     return Uniform(1 << Uniform(max_log + 1));  
    58.   }  
    59. };  

    上述程序运行的结果如下图所示:

  • 相关阅读:
    最短路径算法floyd(转)
    Effective Java 笔记(超链接)
    最短路径算法Dijkstra (转)
    散列表(哈希表)工作原理 (转)
    Java标记接口
    java clone方法使用详解(转)
    Effective Java笔记 (转)
    KMP算法中next数组的理解与算法的实现(java语言)
    sqlserver行列调换
    Linq的一些用法
  • 原文地址:https://www.cnblogs.com/sunsky303/p/8868909.html
Copyright © 2011-2022 走看看