// 折半查找
#include <stdio.h>
const int N = 6;
void Insert_Sort(int r[], int n);
int Bin_Search(int a[], int n, int x);
int x, i, j, t;
int main()
{
int a[] = {5, 2, 4, 6, 1, 3};
// 获取数组长度
int n = sizeof(a) / sizeof(int);
// 进行排序
Insert_Sort(a, n);
for(i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
// 查找的数
x = 6;
t = Bin_Search(a, n, x);
if(t != 0)
printf("查找%d成功,序号为%d", x, t);
else
printf("查找失败", t);
getchar();
return 0;
}
// 插入排序
void Insert_Sort(int *r, int n)
{
for(i = 1; i < n; i++)
{
// 记录要插入的值 以免被替换
x = r[i];
for(j = i-1; j >= 0; j--)
{
// 用插入的值挨个进行比较
if(x < r[j])
{
r[j+1] = r[j];
r[j] = x;
}
}
}
}
// 折半查找
int Bin_Search(int a[], int n, int x)
{
int low, high, mid;
low = 0; high = n - 1;
while(low <= high)
{
mid = (low + high) / 2;
if(x == a[mid])
return mid + 1;
else if(x < a[mid])
high = mid - 1;
else
low = mid + 1;
}
return 0;
}
折半查找-C语言
最新推荐文章于 2023-01-31 23:42:23 发布