如何在C语言中使用二分查找法查找数组中的最小元素?
二分查找
- 此方法仅适用于已排序的列表。
- 给定列表被分成两个相等的部分。
- 给定的键与列表的中间元素进行比较。
这里可能出现三种情况,如下所示:
-
如果中间元素与键匹配,则搜索将在此处成功结束。
-
如果中间元素大于键,则搜索将在左侧分区继续进行。
-
如果中间元素小于键,则搜索将在右侧分区继续进行。
输入
未排序的元素列表,键。
输出
- 成功 – 如果找到键
- 不成功 – 否则

key = 20 mid = (low +high) /2

程序 1
以下是使用二分查找法在数组中查找最小元素的C程序:
#include<stdio.h>
int main(){
int a[50], n, i, key, flag = 0, low, mid, high;
printf("enter the no: of elements:");
scanf ("%d",&n);
printf("enter the elements:");
for(i=0; i<n; i++)
scanf( "%d", &a[i]);
printf("enter a key element:");
scanf ("%d", &key);
low = 0;
high = n-1;
while (low<= high ){
mid = (low + high) /2;
if (a[mid] == key){
flag = 1;
break;
}
else{
if (a[mid] > key)
high = mid-1;
else
low = mid+1;
}
}
if (flag == 1)
printf ("search is successful");
else
printf("search is unsuccessful");
return 0;
}
输出
执行上述程序后,将产生以下结果:
Run 1: enter the no: of elements:5 enter the elements: 12 34 11 56 67 enter a key element:45 search is unsuccessful Run 2: enter the no: of elements:3 enter the elements: 12 34 56 enter a key element:34 search is successful
程序 2
下面是另一个使用二分查找法在数组中查找最小元素的C程序:
#include<stdio.h>
void Bmin(int *a, int i, int n){
int j, temp;
temp = a[i];
j = 2 * i;
while (j <= n){
if (j < n && a[j+1] > a[j])
j = j + 1;
if (temp < a[j])
break;
else if (temp >= a[j]){
a[j / 2] = a[j];
j = 2 * j;
}
}
a[j/2] = temp;
return;
}
int binarysearchmin(int *a,int n){
int i;
for(i = n/2; i >= 1; i--){
Bmin(a,i,n);
}
return a[1];
}
int main(){
int n, i, x, min;
int a[20];
printf("Enter no of elements in an array
");
scanf("%d", &n);
printf("
Enter %d elements: ", n);
for (i = 1; i <= n; i++){
scanf("%d", &a[i]);
}
min = binarysearchmin(a, n);
printf("\minimum element in an array is : %d", min);
return 0;
}
输出
执行上述程序后,将产生以下结果:
Enter no of elements in an array 5 Enter 5 elements: 12 23 34 45 56 minimum element in an array is: 12
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP