二分法查找元素位置
普通二分法查找元素:
创新互联专注于企业成都全网营销推广、网站重做改版、迎江网站定制设计、自适应品牌网站建设、HTML5、商城系统网站开发、集团公司官网建设、外贸营销网站建设、高端网站制作、响应式网页设计等建站业务,价格优惠性价比高,为迎江等各大城市提供网站开发制作服务。
#include#include int BinarySearch(int* a, int n, int pos) { int left = 0; int right = n-1; while (left <= right) { int mid = left+(right-left)/2; if(pos == a[mid]) { return mid; } else if(pos < a[mid]) { right = mid - 1; } else { left = mid + 1; } } return -1; } int main() { int arr[10] = {1,2,3,4,5,6,7,8,9,10}; int ret = BinarySearch(arr, 10, 5); printf("pos : %d\n", ret); system("pause"); return 0; }
显示结果:
那如果是查找数组中第一次出现的那个元素,这种方法显然是不可行。
就需要修改一小下下
#include#include int BinarySearch(int* a, int n, int pos) { int left = 0; int right = n-1; while (left <= right) { int mid = left+(right-left)/2; if(pos == a[mid]) { while(mid-1 >= 0 && pos == a[mid-1]) { mid = mid-1; } return mid; } else if(pos < a[mid]) { right = mid - 1; } else { left = mid + 1; } } return -1; } int main() { int arr1[10] = {1,2,3,4,5,6,7,8,9,10}; int arr2[13] = {1,2,3,4,5,5,5,5,6,7,8,9,10}; int ret1 = BinarySearch(arr1, 10, 5); int ret2 = BinarySearch(arr2, 10, 5); printf("pos1 : %d\n", ret1); printf("pos1 : %d\n", ret2); system("pause"); return 0; }
显示结果:
分享标题:二分法查找元素位置
本文网址:http://ybzwz.com/article/ppepig.html