Presentation is loading. Please wait.

Presentation is loading. Please wait.

Binary Search (I) Date: June 17, 2009 Introducer: Hsing-Yen Ann.

Similar presentations


Presentation on theme: "Binary Search (I) Date: June 17, 2009 Introducer: Hsing-Yen Ann."— Presentation transcript:

1 Binary Search (I) Date: June 17, 2009 Introducer: Hsing-Yen Ann

2 2 問題 給定範圍 [L,U] ,計算範圍內有多少個質 數。 假設 0 < L,U < 1,000,000 Sieve ( 篩法 ) Linear scan ?? 1 999999 2 999998 3 999997 4 999996 … 500000 500000

3 3 解法 先用 Sieve 找出 [0, 1000000] 之間全部的 質數,並存到一個 array 中。 分別用 L 和 U ,在 array 中做 binary search , 找到應該插入的索引位置。 索引位置相減,即是質數的數量。

4 4 圖解 L=5, U=13 L=4, U=13 L=4, U=14 012345678 23571113171923 23571113171923 012345678 23571113171923

5 5 函式庫 C library 若找到則傳回 pointer ;找不到傳回 null C++ library 若找到則傳回 true ;找不到傳回 false Java library 若找到則傳回索引;否則傳回可插入的位置 ( 負號 ) result = bsearch(&key, argv, argc, sizeof(char *), compare); bool found_it = binary_search(&ia[0], &ia[12], 18);

6 6 Binary Search — C++ Code Converted from Java /** * find key in a given range [low, high] of array a * low, high 均為包含 */ int binarySearch(int a[], int key, int low, int high) { while (low <= high) { int mid = (low + high) >> 1; int midVal = a[mid]; if (midVal < key) low = mid + 1; else if (midVal > key) high = mid - 1; else return mid; // key found } return -(low + 1); // key not found. } int idx = binarySearch(a, key, L, U); idx = (idx < 0) ? -idx-1 : idx;


Download ppt "Binary Search (I) Date: June 17, 2009 Introducer: Hsing-Yen Ann."

Similar presentations


Ads by Google