二分查找
Posted 厚德载物
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了二分查找相关的知识,希望对你有一定的参考价值。
正常的二分查找,头尾不断替换,每次砍掉一半
#define _CRT_SECURE_NO_WARNINGS
#include<stdlib.h>
#include<stdio.h>
#define N 1024
void search(int a[N],int num) //二分查找法
{
int tou = 0;
int wei = N - 1;
int zhong;
int flag = -1;
int ci = 0;
while (tou<=wei)
{
zhong = (tou + wei) / 2;
if (num==a[zhong])
{
ci++;
printf("找到,a[%d]=%d", zhong, num);
flag = 1;
break;
}
else if (num > a[zhong])
{
tou = zhong + 1;
}
else
{
wei = zhong - 1;
}
}
if (flag == -1)
{
printf("没有找到");
}
}
拉格朗日二分查找,每次砍掉一大半
void searchL(int a[N], int num) //拉格朗日查找法
{
int tou = 0;
int wei = N - 1;
int zhong;
int flag = -1;
int ci = 0;
while (tou <= wei)
{
zhong = tou+(wei-tou)*1.0*(num-a[tou])/(a[wei]-a[tou]);
if (num == a[zhong])
{
printf("找到,a[%d]=%d,%d", zhong, num,++ci);
flag = 1;
break;
}
else if (num > a[zhong])
{
tou = zhong + 1;
}
else
{
wei = zhong - 1;
}
}
if (flag == -1)
{
printf("没有找到");
}
}
void main()
{
int a[N];
for (int i = 0; i < N; i++)
{
a[i] = i;
printf("%d", i);
}
int num;
scanf("%d", &num);
searchL(a, num);
system("pause");
}
以上是关于二分查找的主要内容,如果未能解决你的问题,请参考以下文章