【本文链接】
http://www.cnblogs.com/hellogiser/p/binary-search-for-repeated-element.html
【题目】
给定一个升序排列的自然数数组,数组中包含重复数字,例如:[1,2,2,3,4,4,4,5,6,7,7]。问题:给定任意自然数,对数组进行二分查找,返回数组正确的位置,给出函数实现。注:连续相同的数字,返回第一个匹配位置还是最后一个匹配位置,由函数传入参数决定。
【代码】
C++ Code
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 |
/*
version: 1.0 author: hellogiser blog: http://www.cnblogs.com/hellogiser date: 2014/9/22 */ #include "stdafx.h" #include "iostream" using namespace std; enum MATCH_POS { FIRST, LAST }; int binary_search(int *a, int n, int value) { if(a == NULL || n <= 0) return -1; int low = 0, high = n - 1, mid; while(low <= high) { mid = low + (high - low) / 2; if (value == a[mid]) { return mid; } else if (value < a[mid]) { high = mid - 1; } else { low = mid + 1; } } return -1; } int binary_search_2(int *a, int n, int value, MATCH_POS match) { if(a == NULL || n <= 0) return -1; int low = 0, high = n - 1, mid; //========================== int count = 0; //========================== while(low <= high) { //========================== count ++; //========================== mid = low + (high - low) / 2; if (value == a[mid]) { if (match == FIRST) { if (mid > 0 && a[mid - 1] == a[mid]) { high = mid - 1; } else { //========================== cout << "count = " << count << endl; //========================== return mid; } } else if (match == LAST) { if (mid < n - 1 && a[mid + 1] == a[mid]) { low = mid + 1; } else { //========================== cout << "count = " << count << endl; //========================== return mid; } } } else if (value < a[mid]) { high = mid - 1; } else { low = mid + 1; } } return -1; } void test_base2() { int a[] = {1, 2, 2, 3, 4, 4, 4, 5, 6, 7, 7}; for (int i = 0; i < sizeof(a) / 4; i++) { cout << binary_search_2(a, sizeof(a) / 4, a[i], FIRST) << endl; cout << binary_search_2(a, sizeof(a) / 4, a[i], LAST) << endl; } cout << "=================================" << endl; int a2[] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; for (int i = 0; i < sizeof(a2) / 4; i++) { cout << binary_search_2(a2, sizeof(a2) / 4, a2[i], FIRST) << endl; cout << binary_search_2(a2, sizeof(a2) / 4, a2[i], LAST) << endl; } cout << "=================================" << endl; int a3[1024] = {0}; cout << binary_search_2(a3, sizeof(a3) / 4, 0, FIRST) << endl; cout << binary_search_2(a3, sizeof(a3) / 4, 0, LAST) << endl; } void test_main() { test_base2(); } int main(void) { test_main(); return 0; } |
由此可知,如果数组有1024个重复元素0,那么查找任然是只需要10次即可。
【参考】