編程珠璣之二分搜索

問題:使用二分搜索返回找到元素的位置,找到第一次出現的位置,找到最後一次出現的位置,分別使用循環和遞歸編寫代碼

原始的二分搜索

int bs(int *a, int low, int high, int target){
	while(low < high){
		if(a[low] == target) return low;
		int mid = (low+high)/2;
		if(a[mid] < target) low = mid + 1;
		if(a[mid] == target) return mid;
		if(a[mid] > target) high = mid - 1;
	}
else
return -1;
}

找到第一次出現的位置
int bs(int *a, int low, int high, int target){
	while(low < high){
		int mid = (low+high)/2;
		if(a[mid] < target) low = mid + 1;
		else high = mid;
	}
	return low;
	if(low > high || !a) return -1;
}

找到最後一次出現的位置

int bs(int *a, int low, int high, int target){
	while(low < high){
		int mid = (low+high+1)/2;
		std::cout<<mid<<std::endl;
		if(a[mid] > target) high = mid - 1;
		else low = mid;
	}
	return high;
	if(low > high || !a) return -1;
}
使用遞歸方法

原始二分搜索

int bs(int *a, int low, int high, int target){
	if(low > high || !a) return -1;
	int mid  = (low + high) / 2;
	std::cout<<mid<<std::endl;
	if(a[mid] == target) return mid;
	if(a[mid] < target) return bs(a,mid+1,high,target);
	if(a[mid] > target) return bs(a,low,mid-1,target);
}
返回第一次出現的位置

int bs(int *a, int low, int high, int target){
	if(low > high || !a) return -1;
	if(low == high) return low;
	int mid  = (low + high) / 2;
	if(a[mid] < target) return bs(a,mid+1,high,target);
	else return bs(a,low,mid,target);
}

返回最後一次出現的位置

int bs(int *a, int low, int high, int target){
	if(low > high || !a) return -1;
	if(low == high) return high;
	int mid  = (low + high + 1) / 2;
	if(a[mid] > target) return bs(a,low,mid-1,target);
	else return bs(a,mid,high,target);
}

測試代碼
#include <iostream>
int main(){
	int a[] = {0,1,1,2,2,2,3,4,5,7,7,7,8,10};
	//int a[] = {0,1,2,3,4,5,6,7};
	int res = bs(a,0,13,7);
	std::cout<<res<<std::endl;
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章