[c++]代码库
#include <iostream>
using namespace std;
#include <stdlib.h>
int linear_search(int arr[],int len,int key )
{
int i;
for(i=0;i<len;i++)
if(arr[i]==key)
break;
if(i<len)
return i;
else return 0;
}
int better_search(int arr[],int len,int key ){
int i;
for(i=len-1;i>=0;i--)
if(arr[i]==key)
break;
return i;
}
int sentinel_search(int arr[],int len,int key ){
int i;
int last;
last = arr[len-1];
arr[len-1]=key;
for(i=0;arr[i]!=key;i++)
if(arr[i]==key)
break;
/*return i;
if(last==key)
return len-1;
else
return -1;
*/
arr[len-1]=last;
if(i<len-1||arr[len-1]==key) return i;
else return -1;
}
int main()
{
int arr[]={1,2,3,4,5,6,7,8,9,10};
printf("%d\n",linear_search(arr,10,3));
printf("%d\n",better_search(arr,10,3));
printf("%d\n",sentinel_search(arr,10,3));
return 0;
}
by: 发表于:2017-12-13 10:33:26 顶(0) | 踩(0) 回复
??
回复评论