[算法] 彻头彻尾理解二分检索 6 种变换

#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <vector>
#include <stack>
#include <deque>
#include <queue>
#include <bitset>
#include <list>
#include <map>
#include <set>
#include <iterator>
#include <algorithm>
#include <functional>
#include <utility>
#include <sstream>
#include <climits>
#include <cassert>
#define BUG puts("here!!!");

using namespace std;
int firstEqual(int *arr, int n, int key) {
	int l = 0, r = n-1;
	while(l <= r) {
		int mid = (l+r) /2;
		if(arr[mid] >= key) r = mid - 1;
		else l = mid + 1;
	}
	if(l < n && arr[l] == key) return l;
	return -1;
}
int firstEqualOrLarge(int *arr, int n, int key) {
	int l = 0, r = n-1;
	while(l <= r) {
		int mid = (l+r) /2;
		if(arr[mid] >= key) r = mid - 1;
		else l = mid + 1;
	}
	return l;
}
int lastSmaller(int *arr, int n, int key) {
	int l = 0, r = n-1;
	while(l <= r) {
		int mid = (l+r) /2;
		if(arr[mid] >= key) r = mid - 1;
		else l = mid + 1;
	}
	return r;
}
int lastEqual(int *arr, int n, int key) {
	int l =  0, r = n-1;
	while(l <= r) {
		int mid = (l + r) / 2;
		if(arr[mid] > key) r = mid - 1;
		else l = mid + 1;
	}
	if(r >= 0 && arr[r] == key) return r;
	return -1;
}
int firstLarge(int *arr, int n, int key) {
	int l =  0, r = n-1;
	while(l <= r) {
		int mid = (l + r) / 2;
		if(arr[mid] > key) r = mid - 1;
		else l = mid + 1;
	}
	return l;
}
int lastEqualOrSmaller(int *arr, int n, int key) {
	int l =  0, r = n-1;
	while(l <= r) {
		int mid = (l + r) / 2;
		if(arr[mid] > key) r = mid - 1;
		else l = mid + 1;
	}
	return r;
}
int main() {
	return 0;
}

posted @ 2013-02-07 09:43  小尼人00  阅读(145)  评论(0编辑  收藏  举报