今天去面試考了binary Search.....
寫了一個recursive version
但是有些語法 錯誤,今天用電腦重新又寫了一個。
intput : array, valuern
output : index (the data index of the array)
note: if not found return -1
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int BinarySearch (int arr[],int value,int s,int l);
int main (void)
{
int array1[] ={-5,1,5,30,70,90,98,99};
int arraysize = sizeof(array1)/sizeof(int);
int findvalue = 99;
int findindex = -1;
int i =0;
findindex = BinarySearch(array1,findvalue,0,arraysize-1);
printf("\nSearh index is:");
printf("%d\n",findindex);
return 0;
}
int BinarySearch (int arr[],int value,int s,int l)
{
if(s<=l)
{
int i = floor((s+l)/2);
if(arr[i] == value)
return i;
else
if(arr[i]>value)
return BinarySearch(arr,value,0,i-1);
else
return BinarySearch(arr,value,i+1,l);
}
return -1;
}
以下是Iterative version
int BinarySearchI(int arr[],int value, int l)
{
int s=0;
while(s<=l)
{
int i = floor((s+l)/2);
if(arr[i] == value)
return i;
else
if(arr[i]>value)
l=i-1;
else
s=i+1;
}
return 0;// not found
}
沒有留言:
張貼留言