二分查找练习
#include <stdio.h> /*非递归二分*/ int HalfSearch(int a[], int low, int high, int key) { while(low <= high) { int mid = (low + high) / 2; if(a[mid] > key) { high = mid - 1; } else if(a[mid] < key) { low = mid + 1; } else { return mid; } } } /*递归二分*/ int HalfSearch2(int a[], int low, int high, int key) { int mid = (low + high) / 2; if (low >= high) { return mid; } if (a[mid] > key) mid = HalfSearch2(a, low, mid - 1, key); else if(a[mid] < key) mid = HalfSearch2(a, mid + 1, high, key); } /*找到第一个等于key的下标*/ int HalfSearch3(int a[], int low, int high, int key) { while(low <= high) { int mid = (low + high) / 2; if(a[mid] > key) { high = mid - 1; } else if(a[mid] < key) { low = mid + 1; } else { if ((0 == mid) || (a[mid - 1] != key)) { return mid; } else { high = mid - 1; } } } } /*找到最后一个等于key的下标*/ int HalfSearch4(int a[], int low, int high, int key) { int n = high; while(low <= high) { int mid = (low + high) / 2; if(a[mid] > key) { high = mid - 1; } else if(a[mid] < key) { low = mid + 1; } else { if ((n == mid) || (a[mid + 1] != key)) { return mid; } else { low = mid + 1; } } } } /*找到第一个大于或等于key的下标*/ int HalfSearch5(int a[], int low, int high, int key) { while(low <= high) { int mid = (low + high) / 2; if(a[mid] >= key) { if ((0 == mid) || (a[mid - 1] < key)) { return mid; } else { high = mid - 1; } } else if(a[mid] < key) { low = mid + 1; } } } /*找到最后一个小于或等于key的下标*/ int HalfSearch6(int a[], int low, int high, int key) { int n = high; while(low <= high) { int mid = (low + high) / 2; if(a[mid] >= key) { high = mid - 1; } else if(a[mid] <= key) { if ((n == mid) || (a[mid + 1] > key)) { return mid; } else { low = mid + 1; } } } } int main() { int i = 0; int a[10] = {2, 9, 4, 1, 3, 55, 46, 15, 10, 32}; int b[10] = {1, 22, 30, 30, 30, 56, 60, 60, 90, 91}; // for (i = 0; i < 10; i++) // { // printf("a[%d]:%d\n", i, a[i]); // }s printf("%d\n", HalfSearch6(b, 0, 9, 50)); return 0; }