二分查找也屬於順序表查找範圍,二分查找也稱爲折半查找。二分查找(有序)的時間複雜度爲O(LogN)。算法
那麼什麼是二分查找呢?二分查找的基本思想是, 在有序表中,取中間記錄做爲比較對象,若給定值與中間記錄的關鍵字相等,則查找成功;若給定值小於中間記錄的關鍵字,則在中間記錄的左半區繼續查找;若給定值大於中間記錄的關鍵字,則在中間記錄的右半區繼續查找。不斷重複上述過程,直到找到爲止。數組
從二分查找的定義咱們能夠看出,使用二分查找有兩個前提條件:spa
1,待查找的列表必須有序。code
2,必須使用線性表的順序存儲結構來存儲數據。對象
下面是實現代碼。blog
C#版:get
namespace BinarySearch.CSharp { class Program { static void Main(string[] args) { List<int> list = new List<int> { 10,20,30,40,50,60,70,80,90 }; Console.WriteLine("********************二分查找********************\n"); Display(list); int result = BinarySearch(list, 40); if (result != -1) Console.WriteLine("40在列表中的位置是:{0}", result); else Console.WriteLine("對不起,列表中不存在該元素!"); Console.ReadKey(); } /// <summary> /// 二分查找 /// </summary> /// <param name="list">查找表</param> /// <param name="key">給定值</param> /// <returns>給定值在列表中的位置</returns> public static int BinarySearch(List<int> list, int key) { int low = 0; int high = list.Count - 1; while (low <= high) { int middle = (low + high) / 2; //判斷中間記錄是否與給定值相等 if (list[middle] == key) { return middle; } else { //在中間記錄的左半區查找 if (list[middle] > key) high = middle - 1; //在中間記錄的右半區查找 else low = middle + 1; } } //沒有找到(查找失敗) return -1; } private static void Display(IList<int> list) { Console.WriteLine("\n**********展現結果**********\n"); if (list != null && list.Count > 0) { foreach (var item in list) { Console.Write("{0} ", item); } } Console.WriteLine("\n**********展現完畢**********\n"); } } }
程序輸出結果如圖:string
C語言版:it
/*包含頭文件*/ #include "stdio.h" #include "stdlib.h" #include "io.h" #include "math.h" #include "time.h" #define OK 1 #define ERROR 0 #define TRUE 1 #define FALSE 0 #define MAXSIZE 20 typedef int Status; typedef struct { int data[MAXSIZE]; int length; }SeqList; /*二分查找算法(折半查找)*/ int BinarySearch(SeqList *seqList,int key) { /*下限*/ int low=0; /*上限*/ int high=seqList->length-1; while(low<=high) /*注意下限能夠與上限重合的*/ { int middle=(low+high)/2; /*判斷中間記錄是否與給定值相等*/ if (seqList->data[middle]==key) { return middle; } else { /*縮小上限*/ if (seqList->data[middle]>key) high=middle-1; /*擴大下限*/ else low=middle+1; } } /*沒有找到*/ return -1; } /*打印結果*/ void Display(SeqList *seqList) { int i; printf("\n**********展現結果**********\n"); for (i=0;i<seqList->length;i++) { printf("%d ",seqList->data[i]); } printf("\n**********展現完畢**********\n"); } #define N 9 void main() { int i,j; SeqList seqList; //定義數組和初始化SeqList int d[N]={10,20,30,40,50,60,70,80,90}; for (i=0;i<N;i++) { seqList.data[i]=d[i]; } seqList.length=N; printf("***************二分查找(C版)***************\n"); Display(&seqList); j=BinarySearch(&seqList,40); if (j!=-1) printf("40在列表中的位置是:%d\n",j); else printf("對不起,沒有找到該元素!"); getchar(); }
程序輸出結果如圖:io