阿里笔试的时候考了,回来写了下。
#include <iostream> using namespace std; int BinarySearch(int array[], int lenght, int key) { int low = 0; int high = lenght - 1; int mid; while (low <= high){ mid = (low + high)/2; if(array[mid] == key){ printf("%d ",array[mid]); return array[mid]; } else if(array[mid] > key) high = mid - 1; else low = mid + 1; } return -1; } void test0() { int array[10] = {0,1,2,3,4,5,6,7,8,9}; if(BinarySearch(array, 10, 5) == 5) { printf("-------------------------passed "); } else { printf("-------------------------failed "); } } void test1() { int array[10] = {0,1,2,3,4,5,6,7,8,9}; if(BinarySearch(array, 10, 15) == -1) { printf("-------------------------passed "); } else { printf("-------------------------failed "); } } void test2() { int array[1] = {0}; if(BinarySearch(array, 1, 15) == -1) { printf("-------------------------passed "); } else { printf("-------------------------failed "); } } void test3() { int array[1] = {0}; if(BinarySearch(array, 1, 0) == 0) { printf("-------------------------passed "); } else { printf("-------------------------failed "); } } void test4() { int array[10] = {0,1,2,3,4}; if(BinarySearch(array, 5, 4) == 4) { printf("-------------------------passed "); } else { printf("-------------------------failed "); } } int main() { test0(); test1(); test2(); test3(); test4(); }