顺序查找:
#include<stdio.h>
#include<stdlib.h>
#define LENGTH 5
int main(void) {
int a[LENGTH] = { 1,3,5,7,11 };
int x;
printf("Please enter the number you want to find:");
scanf_s("%d", &x);
for (int i = 0; i < LENGTH; i++) {
if (x == a[i]) {
printf("find out %d,It is the %dth number in the array\n", x, i + 1);
return 0; //找到了就直接退出程序
}
}
printf("%d does not exist!\n", x);
system("pause");
return 0;
}
二分查找:
比如,在 1,3,5,7,9 五个数
找3是否存在,3和5不对,再分别和1,3比较,总共花了3次
找5是否存在,和中间元素比对直接存在
找11是否存在,...
二分查找要比顺序查找执行效率高
区别:
顺序查找:无要求
二分查找:必须是有序数组