在整型有序数组中查找想要的数字.(折半查找) 谁借莪1个温暖的怀抱¢ 2022-02-20 10:17 150阅读 0赞 折半查找是搜索方法中比较简单的方法,折半查找法虽然比较容易上手,效率比较高,可是局限性比较大,需要在有序数组中查找。 折半查找法就是用你所要查找的数值与中点元素am比较,若X等于am,即找到,停止查找;否则,若X大于am,替换下限l=m+1,到下半段继续查找;若X小于am,换上限h=m-1,到上半段继续查找;如此重复前面的过程直到找到或者l>h为止。如果l>h,说明没有此数,打印找不到信息,程序结束。 以下是我写的折半查找法: 此环境在vs环境下运行: #define _CRT_SECURE_NO_WARNINGS 1 #include<stdio.h> #include<stdlib.h> int bisearch(int a[],int i,int q,int k) { int u; while (q<=k){ if (a[q + (k-q) / 2] == i) { break; } if (a[q + (k-q) / 2] > i) { k = q + (k-q) / 2 - 1; } if (a[q + (k-q) / 2] < i) { q = q + (k-q) / 2 + 1; } } u = q + (k - q) / 2; return u; } int main() { int a[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int i; scanf("%d",&i); int k = sizeof(a) / sizeof(a[0]) - 1; int q = 0; q=bisearch(a,i,q,k); printf("%d\n", q); }
还没有评论,来说两句吧...