简单的二分查找(CC++实现)

    技术2022-07-10  102

    二分查找适用于已经排好序的数组,二分查找的平均(时间)复杂度远比顺序查找要小得多,在庞大的数据中更明显。 二分查找:

    #include <cstdio> #include <iostream> int main() { int a[10] = {11, 22, 33, 44, 55, 66, 77, 88, 99, 100}, mid, L, R, s = 55; L = 0; R = 9; while (L <= R) { mid = L + (R - L) / 2;//这个比mid=mid/2之类的处理的较好,不会溢出,不用担心mid是否是小数 if (s > a[mid]) L = mid + 1; else if (s < a[mid]) R = mid - 1; else { printf("%d\n", mid); system("pause"); return 0; } } printf("didn't find!\n"); return 0; } /* 输出: 4 */
    Processed: 0.011, SQL: 9