关于索引,我们很容易地联想到数据库中的索引,建立了索引,可以大大提高数据库的查询速度。
索引查找又称为分块查找,是一种介于顺序查找和二分查找之间的一种查找方法,分块查找的基本思想是:首先查找索引表,可用二分查找或顺序查找,然后在确定的块中进行顺序查找。
分块查找的时间复杂度为O(√n)。
查找原理
将n个数据元素“按块有序”划分为m块(m<=n)。
每一块中的节点不必有序,但块与块之间必须“按块有序”:即第一块中任何一元素的关键字都必须小于第二块中任一元素的关键字;
而第二块中任一元素又都必须小于第三块中的任一元素的关键字,......
然后使用二分查找及顺序查找。
在实现索引查找算法前需要弄清楚以下三个术语。
1,主表。即要查找的对象。
2,索引项。一般我们会将主表分成几个子表,每个子表建立一个索引,这个索引就叫索引项。
3,索引表。即索引项的集合。
同时,索引项包括以下三点。
1,index,即索引指向主表的关键字。
2,start,即index在主表中的位置。
3,length,即子表的区间长度。
下面是算法实现代码。
public class IndexItem
{
public int Index { get; set; }
public int Start { get; set; }
public int Length { get; set; }
}
class Program
{
/// <summary>
/// 主表
/// </summary>
static int[] studentList = new int[] {
101,102,103,104,105,0,0,0,0,0,
201,202,203,204,0,0,0,0,0,0,
301,302,303,0,0,0,0,0,0,0
};
/// <summary>
/// 索引表
/// </summary>
static IndexItem[] IndexItemList = new IndexItem[] {
new IndexItem{ Index=1,Start=0,Length=5},
new IndexItem{ Index=2,Start=10,Length=4},
new IndexItem{ Index=3,Start=20,Length=3}
};
public static int IndexSearch(int key)
{
IndexItem item = null;
//索引规则
//为了找到对应的表
var index = key / 100;
//遍历索引表,找到对应的索引项
for (int i = 0; i < IndexItemList.Count(); i++)
{
//找到索引项
if(IndexItemList[i].Index == index)
{
item = new IndexItem() { Start = IndexItemList[i].Start, Length = IndexItemList[i].Length };
break;
}
}
if (item == null) return -1;
//在主表中顺序查找
for (int i = item.Start; i < item.Start + item.Length; i++)
{
if(studentList [i] == key )
{
return i;
}
}
return -1;
}
/// <summary>
/// 插入数据
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public static bool Insert(int key)
{
IndexItem item = null;
try
{
//索引规则
//为了找到对应的表
var index = key / 100;
int i = 0;
//遍历索引表,找到对应的索引项
for ( i = 0; i < IndexItemList.Count(); i++)
{
if(IndexItemList[i].Index == index)
{
item = new IndexItem()
{
Start = IndexItemList[i].Start,
Length = IndexItemList[i].Length
};
break;
}
}
if (item == null) return false;
studentList[item.Start + item.Length] = key;
IndexItemList[i].Length++;
}
catch
{
return false;
}
return true;
}
static void Main(string[] args)
{
Console.WriteLine("********************索引查找(C#版)********************\n");
Console.WriteLine("原始数据:{0}", String.Join(" ", studentList));
int value = int.Parse(Console.ReadLine());
Console.WriteLine("插入数据:{0}", value);
//插入成功
if (Insert(value))
{
Console.WriteLine("\n插入后数据:{0}", String.Join(",", studentList));
Console.WriteLine("\n元素{0}在列表中的位置为:{1} ",value , IndexSearch(value));
}
Console.ReadKey();
}
}
原文链接 : 点击打开链接