c语言二分查找重复的元素位置
时间: 2023-08-23 11:36:55 浏览: 50
以下是 C 语言的二分查找重复元素位置的示例代码:
```c
#include <stdio.h>
int binary_search(int arr[], int left, int right, int target) {
while (left <= right) {
int mid = (left + right) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
int main() {
int arr[] = {1, 2, 2, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int target = 2;
int first_pos = binary_search(arr, 0, n - 1, target);
if (first_pos == -1) {
printf("Element not found\n");
return 0;
}
int last_pos = first_pos;
while (last_pos < n && arr[last_pos] == target) {
last_pos++;
}
last_pos--;
printf("The target element %d is found between positions %d and %d\n", target, first_pos, last_pos);
return 0;
}
```
该代码中,我们首先使用二分查找算法找到第一个等于目标元素的位置。然后从该位置开始,我们向右遍历数组,找到最后一个等于目标元素的位置。这样,我们就可以确定重复元素的起始和结束位置。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)