C#实现跳跃表查找(Skip List Search)算法
下面是一个使用 C# 实现跳跃表查找(Skip List Search)算法的示例代码:
using System;
public class Node
{
public int Value { get; set; }
public Node[] Forward { get; set; }
public Node(int value, int level)
{
Value = value;
Forward = new Node[level + 1];
}
}
public class SkipList
{
private const int MaxLevel = 16;
private readonly Node head = new Node(-1, MaxLevel);
private int level;
private readonly Random random = new Random();
// Generate a random level for the new node
private int RandomLevel()
{
int lvl = 0;
while (random.Next() % 2 == 0 && lvl < MaxLevel)
{
lvl++;
}
return lvl;
}
// Insert a value into the skip list
public void Insert(int value)
{
Node[] update = new Node[MaxLevel + 1];
Node current = head;
for (int i = level; i >= 0; i--)
{
while (current.Forward[i] != null && current.Forward[i].Value < value)
{
current = current.Forward[i];
}
update[i] = current;
}
int lvl = RandomLevel();
if (lvl > level)
{
for (int i = level + 1; i <= lvl; i++)
{
update[i] = head;
}
level = lvl;
}
Node newNode = new Node(value, lvl);
for (int i = 0; i <= lvl; i++)
{
newNode.Forward[i] = update[i].Forward[i];
update[i].Forward[i] = newNode;
}
}
// Search for a value in the skip list
public bool Search(int value)
{
Node current = head;
for (int i = level; i >= 0; i--)
{
while (current.Forward[i] != null && current.Forward[i].Value < value)
{
current = current.Forward[i];
}
}
current = current.Forward[0];
return current != null && current.Value == value;
}
public static void Main(string[] args)
{
SkipList skipList = new SkipList();
skipList.Insert(1);
skipList.Insert(3);
skipList.Insert(7);
skipList.Insert(8);
skipList.Insert(9);
Console.WriteLine("Search for 3: " + skipList.Search(3)); // Output: True
Console.WriteLine("Search for 6: " + skipList.Search(6)); // Output: False
}
}
这个 C# 实现包含了以下主要部分:
- Node 类:表示跳跃表中的节点,包含一个值和一个指针数组。
- SkipList 类:包含插入和查找方法,以及一个随机数生成器用于确定新节点的层级。
- RandomLevel 方法:生成一个随机的层级,用于新节点。
- Insert 方法:在跳跃表中插入一个值,更新相应的指针。
- Search 方法:在跳跃表中查找一个值,返回一个布尔值表示是否找到。
- Main 方法:测试插入和查找功能。
这段代码展示了如何实现和使用跳跃表进行快速查找。