【编程题】二分查找

void BinarySearch(int a[],int n,int key) {
	int left = 0, right = n-1;   //初始化左右
	while (left<=right) {
		int mid = (left + right) / 2;  //二分查找的下标
		if (a[mid] > key)right = mid-1;
		else if (a[mid] < key)left = mid+1;
		else {
			cout<<"position==="<< mid<<endl;
			return;
		}
	}
	cout<<"查找失败!"<<endl;
}

 

### PTA C语言编程题二分查找 #### 二分查找简介 二分查找是一种高效的搜索算法,适用于已排序的数据序列。该方法通过反复将待查区间减半来快速定位目标值的位置[^2]。 #### 实现方式 对于PTA平台上涉及的C语言编程题目中的二分查找问题,通常有两种主要实现途径: - **基于函数的方式** 这种方法把二分查找逻辑封装在一个独立的功能模块内,便于维护和重用。下面是一个简单的例子: ```c #include <stdio.h> // 定义二分查找函数 int binarySearch(int arr[], int l, int r, int x) { while (l <= r) { int m = l + (r - l) / 2; // 检查中间位置是否为目标值 if (arr[m] == x) return m; // 如果目标值大于位于mid处的数组元素,则忽略左半部分 if (arr[m] < x) l = m + 1; // 否则忽略右半部分 else r = m - 1; } // 若未找到返回-1 return -1; } int main(void) { int arr[] = {2, 3, 4, 10, 40}; int n = sizeof(arr)/sizeof(arr[0]); int x = 10; int result = binarySearch(arr, 0, n-1, x); (result == -1)? printf("Element not present") : printf("Element found at index %d", result); return 0; } ``` - **不使用额外定义函数的方式** 这种方式直接在`main()`函数内部完成整个流程控制,适合较为简单的情况或是初学者练习时采用。这里给出一段简化版本作为示范: ```c #include <stdio.h> #define SIZE 5 int main(){ int array[SIZE]={2,3,4,10,40}; // 假设已经按升序排列好的数据集合 int target=10; // 要找的目标数值 int low=0,high=SIZE-1,mid=-1; while(low<=high){ mid=(low+high)/2; if(array[mid]==target){ printf("Found the element at position:%d\n",mid); break; }else if(target<array[mid]){ high=mid-1; }else{ low=mid+1; } } if(mid==-1 || array[mid]!=target){ printf("The given number is not in this list.\n"); } return 0; } ``` 上述两段代码展示了如何利用不同的结构去解决问题,在实际应用过程中可以根据具体需求和个人偏好做出适当调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值