C语言 二分法查找之面试题

#include
#include
#include

//二分法 递归 
int binarysearch(int *arr, int begin, int end, int val){
	if(begin < 0 || end < 0 || begin > end){
		return -1;
	}
	int middle = (begin + end)/2;
	if(arr[middle] == val){
		return 1;
	}else if(val < arr[middle]){
		return binarysearch(arr, begin, middle-1, val);
	}else{
		return binarysearch(arr, middle+1, end, val);
	}
	return 0;
}
// 二分法 迭代 
int binarysearch02(int *arr, int begin, int end, int val){
	if(begin < 0 || end < 0){
		return -1;
	}
	int middle;
	while(begin <= end){
		middle = (begin+end)/2;
		if(arr[middle] == val){
			return 1;
		}else if(val < arr[middle]){
			end = middle - 1;
		}else{
			begin = middle + 1;
		}
	}
	return 0;
}
int isInRange(int beginNum, int endNum, int val){
	if(val >= beginNum && val <= endNum){
		return 1;
	}
	return 0;
}
//在 3,4,5,1,2中查找指定值 
int rotateBinarySearch(int *arr, int begin, int end, int val){
	if(begin < 0 || end < 0 || begin > end){
		return -1;
	}
	int middle;
	while(begin <= end){
		middle = (begin + end + 1)/2;
		if(arr[middle] == val){
			return middle;
		}
		if(arr[middle] >= arr[begin]){
			if(isInRange(arr[begin], arr[middle-1], val)){
				end = middle - 1;
			}else{
				begin = middle + 1;
			}
		}else{
			if(isInRange(arr[middle+1], arr[end], val)){
				begin = middle + 1;
			}else{
				end = middle - 1;
			}
		}
	}
	return 0;
}
// 在 3,4,5,1,2中查找最小值 
int findMinNum(int *arr, int begin, int end){
	if(begin < 0 || end < 0){
		return -1;
	}
	if(arr[end] > arr[begin]){
		return arr[begin];
	}else{
		int middle;
		while(begin <= end){
			middle = (begin + end + 1)/2;
			if(arr[middle] < arr[middle-1] && arr[middle] < arr[middle+1]){
				return arr[middle];
			}else if(arr[middle] > arr[begin] && arr[middle] > arr[end]){
				begin = middle + 1;
			}else{
				end = middle - 1;
			}
		}
	}
	return 0;
}
//在1,2,2,3,4,5,7,7 查找指定数值重复次数 
int findSameNumCount(int *arr, int begin, int end, int val){
	if(begin < 0 || end < 0 || begin > end){
		return -1;
	}
	int middle;
	int temp01;
	int temp02;
	while(begin <= end){
		middle = (begin + end + 1)/2;
		if(arr[middle] == val){
			temp01 = middle;
			temp02 = middle;
			while(arr[temp01] == val){
				temp01--;
			}
			while(arr[temp02] == val){
				temp02++;
			}
			return temp02-temp01-1;
		}else if(val < arr[middle]){
			end = middle - 1;
		}else{
			begin = middle + 1;
		}
	}
	return 0;
}
//在二维数组中查找指定数值 
int findNumInArray(int arr[], int h, int c, int val){
	if(h < 0 || c < 0 || val < 0){
		return -1;
	}
	int temp;
	int iRow = 0;
	int iCol = c-1;
	while(iRow < h && iCol >= 0){
		temp = arr[iRow][iCol];
		if(temp == val){
			return 1;
		}else if(val < temp){
			iCol--;
		}else{
			iRow++;
		}
	}
	return 0;
}
int main(){
	int num[9] = {1, 2, 2, 3, 3, 3, 4, 5, 5};
	//int num[9] = {2, 2, 2, 2, 2, 2, 2, 2, 2};
	int result = findSameNumCount02(num, 0, 8, 3);
	printf("%d\n", result);
	return 0;
}

你可能感兴趣的:(C语言,c语言,二分查找,面试题)