C++编写二分查找
#pragma warning (disable:4996)
#include <iostream>
#include <string>
#include <conio.h>
#include <fstream>
#include <iomanip>
#include <stdio.h>
#include <vector>
#include "list_node.h"
using namespace std;
int search(const int(&a)[10], int start, int end, int target) {
if (target < a[start] || target > a[end] || start > end) {
return -1;
}
int mid = (start + end) / 2;
if (a[mid] == target) {
return mid;
}
if (a[mid] < target) {
return search(a, mid + 1, end, target);
}
else {
return search(a, start, mid - 1, target);
}
}
int main(void) {
int arr[10] = { 1, 2, 3, 4, 5, 6, 7, 9, 11, 25 };
int target = 11;
int result = search(arr, 0, (sizeof(arr) / sizeof(arr[0]))-1, target);
result == -1 ? cout << "没有找到你要查找的目标!" << endl :
cout << "你所查找的目标在数组的第" << result + 1 << "个位置" << endl;
system("pause");
return 0;