二分查找
一、判断一个数是否为素数
素数:在大于1的自然数中,除了1和它本身,不再有其他因数的自然数
int checkNumber(int number) { if (number < 2) { return 0; } for (int i = 2; i < number; i++) { if (number % i == 0) { return -1; } } return 1; }
二、递归实现二分查找
int binarySearch(int key,int data[],int low,int high) { if (low >= high) { return -1; } int mid = (low + high) / 2; if (key < data[mid]) { return binarySearch(key,data,low,mid); } else if(key >data[mid]){ return binarySearch(key,data,mid+1,high); } else { return mid; } }
递归耗时: 44 ms
三、循环实现二分查找
int binarySearch(int* data,int size,int target) { int left = 0; int right = size - 1; while (left <= right) { int mid = (left + right) / 2; if (target > data[mid]) { left = mid + 1; } else if(target < data[mid]){ right = mid - 1; } else { return mid; } } return -1; }
耗时:32 ms