C++顺序表折半查找
算法思想 折半查找:又称二分查找,适用于有序的顺序表。 先将中间位置元素与Key进行比较 若相等,则返回中间位置下标 若不相等: ① key<中间值,在左半边继续查找 ② key>中间值,在右半边继续查找 算法实现 int BinarySearch ( sqList L , int key ) { int low = 0 , high = L . length - 1 ; while ( low <= high ) //'<='很关键 { int mid = ( low + high ) / 2 ; if ( L . data [ mid ] == key ) return mid + 1 ; else if ( key < L . data [ mid ] ) high = mid - 1 ; else low = mid + 1 ; } return - 1 ; } 运行代码 # include "stdafx.h" # include <iostream> using namespace std ; # define MaxSize 50 typedef struct { int data [ MaxSize ] ; int length ; } sqList ; void Creat ( sqList & L ) ; int Search ( sqList L , int