二分法
#include <stdio.h> #include <string.h> #include <stdlib.h> int paixu(int *a); int chazhao(int *a,int b); int main() { int a[10] = { 2, 56, 58, 685, 459, 32, 1, 52, 68, 45 }; paixu(a); int xiabiao = 0; xiabiao = chazhao(a, 685); printf("%d\n", xiabiao); return 0; } int paixu(int *a) { int len = sizeof(a); for (int i = 0; i < len; i++) { for (int j = 0; j < len - 1; j++) { if (a[j] < a[j + 1]) { int tmp = a[j]; a[j] = a[j + 1]; a[j + 1] = tmp; } } } } int chazhao(int *a, int b) //b为想查找的数据 { //下标 int xiabiao = 0; //区域下限 int low = 0; //区域上限 初次上限取为数组的最大宽度 int high = sizeof(a); //二分法取得中间值 int middle; while (high > low) { //一开始中间值为数组的中间 middle = (low + high) / 2; //判断直到当b等于中间值时 输出中间值的下标 if (b == a[middle]) { return middle; } //进行循环时 如果b小于中间值 则更改上限,把刚才的中间值变为上限 if (b < a[middle]) { high = middle-1; } //如果b>中间值,则更改下限 if (b >a[middle]) { low = middle+1; } } }
思路:
取数组的首位下标作为上下限
取其中间值作为基准
用待查找值和中间值所对应的数字对比
如果不相等,则判断大小,并且重新划分区域
循环更改上下限重复查找
#include <stdio.h>#include <string.h>#include <stdlib.h>int paixu(int *a);int chazhao(int *a,int b);
int main(){int a[10] = { 2, 56, 58, 685, 459, 32, 1, 52, 68, 45 };paixu(a);int xiabiao = 0;xiabiao = chazhao(a, 685);printf("%d\n", xiabiao);return 0;}
int paixu(int *a){int len = sizeof(a);for (int i = 0; i < len; i++){for (int j = 0; j < len - 1; j++){if (a[j] < a[j + 1]){int tmp = a[j];a[j] = a[j + 1];a[j + 1] = tmp;}}}}
int chazhao(int *a, int b)//b为想查找的数据{//下标int xiabiao = 0;//区域下限int low = 0;//区域上限 初次上限取为数组的最大宽度int high = sizeof(a);//二分法取得中间值int middle;
while (high > low){//一开始中间值为数组的中间middle = (low + high) / 2;//判断直到当b等于中间值时 输出中间值的下标if (b == a[middle]){return middle;}//进行循环时 如果b小于中间值 则更改上限,把刚才的中间值变为上限if (b < a[middle]){high = middle-1;}//如果b>中间值,则更改下限if (b >a[middle]){low = middle+1;}}}