递归分治二分查找法
1: #include "stdio.h"
2:
3: int getFalseCoin(int coin[], int low, int high)
4: {
5: int i, sum1 = 0, sum2 = 0, sum3 = 0;
6:
7: if(low + 1 == high)
8: {
9: if(coin[low] < coin[high]) return low + 1;
10: else return high + 1;
11: }
12:
13: if((high - low + 1) % 2 == 0) /*n是偶数*/
14: {
15: for(i = low; i <= low + (high - low) / 2; i++)
16: sum1 = sum1 + coin[i]; /*前半段和*/
17:
18: for(i = low + (high - low) / 2 + 1; i <= high; i++)
19: sum2 = sum2 + coin[i]; /*后半段和*/
20:
21: if(sum1 < sum2) return getFalseCoin(coin, low, low + (high - low) / 2);
22:
23: if(sum1 > sum2) return getFalseCoin(coin, low + (high - low) / 2 + 1, high);
24: }
25:
26: if((high - low + 1) % 2 != 0)
27: {
28: for(i = low; i <= low + (high - low) / 2 - 1; i++)
29: sum1 = sum1 + coin[i]; /*前半段和*/
30:
31: for(i = low + (high - low) / 2 + 1; i <= high; i++)
32: sum2 = sum2 + coin[i]; /*后半段和*/
33:
34: sum3 = coin[low+(high-low)/2];
35:
36: if(sum1 < sum2)
37: return getFalseCoin(coin, low, low + (high - low) / 2 - 1);
38:
39: if(sum1 > sum2)
40: return getFalseCoin(coin, low + (high - low) / 2 + 1, high);
41:
42: if(sum1 + sum3 == sum2 + sum3) return low + (high - low) / 2 + 1;
43: }
44:
45: }
46:
47: int main()
48: {
49: int coin[30] = {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 2, 2};
50: printf("The %dth coin is false\n", getFalseCoin(coin, 0, 29));
51: return 0;
52: }