關於索引,我們很容易地聯想到數據庫中的索引,建立了索引,可以大大提高數據庫的查詢速度。
索引查找又稱為分塊查找,是一種介於順序查找和二分查找之間的一種查找方法,分塊查找的基本思想是:首先查找索引表,可用二分查找或順序查找,然后在確定的塊中進行順序查找。
分塊查找的時間復雜度為O(√n)。
查找原理
將n個數據元素“按塊有序”划分為m塊(m<=n)。
每一塊中的節點不必有序,但塊與塊之間必須“按塊有序”:即第一塊中任何一元素的關鍵字都必須小於第二塊中任一元素的關鍵字;
而第二塊中任一元素又都必須小於第三塊中的任一元素的關鍵字,......
然后使用二分查找及順序查找。
在實現索引查找算法前需要弄清楚以下三個術語。
1,主表。即要查找的對象。
2,索引項。一般我們會將主表分成幾個子表,每個子表建立一個索引,這個索引就叫索引項。
3,索引表。即索引項的集合。
同時,索引項包括以下三點。
1,index,即索引指向主表的關鍵字。
2,start,即index在主表中的位置。
3,length,即子表的區間長度。
下面是算法實現代碼。
C#版:
namespace IndexSearch.CSharp { /// <summary> /// 索引項實體 /// </summary> public class IndexItem { public int Index { get; set; } public int Start { get; set; } public int Length { get; set; } } public 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} }; /// <summary> /// 索引查找算法 /// </summary> /// <param name="key">給定值</param> /// <returns>給定值在表中的位置</returns> 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>true,插入成功,false,插入失敗</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 = 205; Console.WriteLine("插入數據:{0}",value); //插入成功 if (Insert(value)) { Console.WriteLine("\n插入后數據:{0}",String.Join(",", studentList)); Console.WriteLine("\n元素205在列表中的位置為:{0} ",IndexSearch(value)); } Console.ReadKey(); } } }
程序輸出結果如圖: