1.题目:
用折半查找法在数组 int arr[] = { 1,2,3,4,5,6,7,8,9,10 }; 中找到7的下标
2.常规解
3.自定义函数解
4.注意点:
别把下标的位置值和元素搞混了!
5.源码
(1)常规解源码:
#include <stdio.h> //来引入打印函数printf
int main()
{
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
int k = 7; //查找的对象
int sz = sizeof(arr) / sizeof(arr[0]);
int left = 0; //最左面元素的下标
int right = sz - 1; //最右面元素的下标
while (left <= right)
{
int mid = (left + right) / 2; //中间元素的下标
if (arr[mid] > k)
{
right = mid - 1;
}
else if (arr[mid] < k)
{
left = mid + 1;
}
else
{
printf("找到了,下标是:%d\n", mid);
break;
}
}
if (left > right)
{
printf("找不到了\n");
}
return 0;
}
(2)自定义函数解源码:
#include <stdio.h> //来引入打印函数printf
int binary_search(int k,int sz,int arr[])
{
int left = 0;
int right = sz - 1;
while (left <= right)
{
int mid = (left + right) / 2; //mid是下标
if (arr[mid] < k)
{
left = mid + 1;
}
else if (arr[mid] > k)
{
right = mid - 1;
}
else
{
return mid;
break;
}
} //找到了就返回位置的下标
if (left >= right) //找不到就返回-1
{
return -1;
}
}
int main()
{
int arr[] = {1,2,3,4,5,6,7,8,9,10};
int k = 7;
int sz = sizeof(arr) / sizeof(arr[0]);
int key = binary_search(k,sz,arr); // binary 二进制的意思
if (-1 == key)
{
printf("找不到");
}
else
{
printf("找到了下标是:%d\n", key);
}
return 0;
}