1: // 二分查找.cpp : 定义控制台应用程序的入口点。
2: //
3:
4: #include "stdafx.h"
5: #include <string.h>
6: #include //int abs(int value)
7: #include
8: using namespace std;
9:
10: int bisearch(int* arr, int beg, int end, int v)//给定一个升序排列的数组的二分查找
11: {
12: int minIndex=beg, maxIndex=end, midIndex;
13: while(minIndex < maxIndex -1 )
14: {
15: midIndex = minIndex + (maxIndex - minIndex) / 2;
16: if(arr[midIndex] - v <= 0)
17: {
18: minIndex = midIndex;
19: }
20: else
21: {
22: maxIndex = midIndex;
23: }
24: }
25: if( arr[maxIndex]-v==0 )
26: {
27: return maxIndex;
28: }
29: else if( arr[minIndex]-v ==0 )
30: {
31: return minIndex;
32: }
33: else
34: return -1;
35: }
36:
37: int _tmain(int argc, _TCHAR* argv[])
38: {
39: //char arr[][]={"c","b","a","j","e","f","l","h","i","d","k","g"};
40: //int arr[11]={0,1,1,1,1,1,1,1,1,2,5};
41: int arr[11]={0,1,2,3,4,5,6,7,8,9,10};
42: int result;
43:
44: result = bisearch(arr, 0, 10, 3);
45: cout<<result;
46:
47: int temp;
48: temp = (2-7) % 10;
49: cout <<endl<<"abs ( (2-7) % 10 ) = "<<abs(temp)<<endl;
50: getchar();
51: return 0;
52: }
53: