1 #include <stdio.h> 2 #include <stdlib.h> 3 4 typedef int ElementType; 5 6 typedef struct { 7 int element[16]; 8 int length; 9 }StaticTable; 10 11 12 //二分法查找 13 int BinarySearch(StaticTable* Tbl, ElementType K) 14 {//在表TB了中查找关键字为K的数据元素 15 int left, right, mid, NotFound = -1; 16 left = 1; //初始左边界 17 right = Tbl->length; //初始右边界 18 while (left <= right) 19 { 20 mid = (left + right) / 2; //计算中间元素坐标 21 if (K < Tbl->element[mid]) right = mid - 1; //调整有边界 22 else if (K > Tbl->element[mid]) left = mid + 1; //调整做边界 23 else return mid; //查找成功,返回数据元素的下标 24 } 25 return NotFound; //查找不成功,返回-1; 26 } 27 28 29 //顺序查找 30 int Index(StaticTable *Tbl, ElementType K) 31 { 32 int i ; 33 Tbl->element[0] = K; 34 for (i = Tbl->length; Tbl->element[i] != K; i--); 35 return i; 36 } 37 38 39 40 int main() 41 { 42 StaticTable * Tb1 = (StaticTable*)malloc(sizeof(StaticTable)); 43 Tb1->length = 15; 44 for (int i = 1; i < 16; i++) 45 { 46 Tb1->element[i] = i + 1; 47 } 48 49 int index1 = BinarySearch(Tb1, 15); 50 printf("%d\n", index1); 51 52 int index2 = Index(Tb1, 5); 53 printf("%d\n", index2); 54 return 0; 55 }