一、二分查找
在C和C++里,二分查找是针对有序数组所用的一种快速查找元素的方法。
二、二分查找的条件以及优缺点
条件:针对有序数组(元素从小到大或从大到小)
优点:查询速度较快,时间复杂度为O(n)
缺点:有硬性条件的限制,而且即使查到后,插入与删除困难。
三、图片详解
四、代码
#define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #define N 15 int main() { int i, number, top, bott, mid, loca, a[N], flag = 1, sign; char c; printf("enter data "); scanf("%d", &a[0]); i = 1; while (i<N) { scanf("%d", &a[i]); if (a[i]>=a[i-1]) { i++; } else { printf("enter this data again: "); } } printf(" "); for (i = 0; i < N; i++) { printf("%5d", a[i]); } printf(" "); while (flag) { printf("input number to look for:"); scanf("%d", &number); sign = 0; top = 0;//top 是查找区间的其实位置 bott = N - 1;//bott是查找区间的最末位置 if ((number<a[0])||(number>a[N-1]))//要查找的数不在查找区间 { loca = -1;//表示找不到 } while ((!sign)&&(top<bott)) { mid = (top + bott) / 2; if (number==a[mid]) { loca = mid; printf("Has found %d,its position is %d ", number, loca + 1); sign = 1; } else if (number < a[mid]) { bott = mid - 1; } else { top = mid + 1; } } if (!sign||loca==-1) { printf("can not find %d. ", number); } printf("continue or not?(Y/N)"); scanf("%c", &c); if (c=='N'||c=='n') { flag = 0; } } }