//Data为要查找的数组,x为待查找数据值,beg为查找范围起始,last为查找范围终止 //非递归法 int BiSearch(int data[], const int x, int beg, int last) { int mid;//中间位置 if (beg > last) { return -1; } while(beg <= last) { mid = (beg + last) / 2; if (x == data[mid] ) { return mid; } else if (data[mid] < x) { beg = mid + 1; } else if (data[mid] > x) { last = mid - 1; } } return -1; } //递归法 int IterBiSearch(int data[], const int x, int beg, int last) { int mid = -1; mid = (beg + last) / 2; if (x == data[mid]) { return mid; } else if (x < data[mid]) { return IterBiSearch(data, x, beg, mid - 1); } else if (x > data[mid]) { return IterBiSearch(data, x, mid + 1, last); } return -1; } //主函数 int _tmain(int argc, _TCHAR* argv[]) { int data1[60] = {0}; int no2search = 45; cout << "The array is : " << endl; int siz = sizeof(data1)/sizeof(int); for (int i = 0; i < siz; i++) { data1[i] = i; cout << data1[i] << " "; } cout << endl; int index = -1; //index = BiSearch(data1, no2search, 0, siz); index = IterBiSearch(data1, no2search, 0, siz); cout << "Index of " << no2search << " is " << index << endl; getchar(); return 0; }
时间: 2024-10-19 09:00:31