折半查找
阿里笔试的时候考了,回来写了下。
#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\n",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\n"); } else { printf("-------------------------failed\n"); } } void test1() { int array[10] = {0,1,2,3,4,5,6,7,8,9}; if(BinarySearch(array, 10, 15) == -1) { printf("-------------------------passed\n"); } else { printf("-------------------------failed\n"); } } void test2() { int array[1] = {0}; if(BinarySearch(array, 1, 15) == -1) { printf("-------------------------passed\n"); } else { printf("-------------------------failed\n"); } } void test3() { int array[1] = {0}; if(BinarySearch(array, 1, 0) == 0) { printf("-------------------------passed\n"); } else { printf("-------------------------failed\n"); } } void test4() { int array[10] = {0,1,2,3,4}; if(BinarySearch(array, 5, 4) == 4) { printf("-------------------------passed\n"); } else { printf("-------------------------failed\n"); } } int main() { test0(); test1(); test2(); test3(); test4(); }
________你所记的,都是假的。