查找
查找元素伪代码
穷举法
Begin
Set num[length] to some number
Set target
Set i to 0
read target
while (i <length) do
if(num[i] == target)
printf("找到了")
break
if(i==length)
printf("没找到")
二分法
Begin
Set num[length] to some number
Set target,left,right
Set i to 0
Set left to num[0]
Set right to num[length-1]
read target
while(left<=right)
Set mid to (left+right)/2
if(num[mid]>target)
right to mid -1
if(num[mid]<target)
left to mid +1
if(num[mid]==target)
printf("找到了")
if(left > right)
printf("找不到")
End
代码实现
二分法代码(仅以该数组和7为例子)
#include <stdio.h>
int main()
{
int arr[10]={1,2,3,4,5,6,7,8,9,10} ;
int left = 0 ;
int right = 0 ;
int a = 7 ;
int i = 1 ;
int n = sizeof(arr) / sizeof(arr[0]) ;
right = n - 1 ;
while (left <= right)
{
int mid = (left+right)/2 ;
if (arr[mid]> a)
{
right = mid - 1 ;
}
if (arr[mid]< a)
{
left = mid + 1 ;
}
if (arr[mid]==a)
{
printf("找到了,下标是:%d",mid);
break;
}
}
if (left > right )
{
printf("找不到") ;
}
return 0 ;
}