1、顺序查找
int sequenceSearch(int a[],int n,int num)
{
for(int i=0;i<n;i++)
{
if(a[i]==num) return i;
}
return -1;
}
for(int i=0;i<n;i++)
{
if(a[i]==num) return i;
}
return -1;
}
2、 二分查找
1)用递归法:
int search1(int a[],int num,int left,int right)
{
int mid=(left+right)/2;
if(a[mid]==num) return mid;
if(left==right) return -1;
if(a[mid]>num) return search1(a,num,left,mid-1);
if(a[mid]<num) return search1(a,num,mid+1,right);
int mid=(left+right)/2;
if(a[mid]==num) return mid;
if(left==right) return -1;
if(a[mid]>num) return search1(a,num,left,mid-1);
if(a[mid]<num) return search1(a,num,mid+1,right);
}
2)不用递归
int halfFind2(int a[],int n,int num)//不用递归
{
int start=0,end=n-1;
while(start<=end)
{
int mid=(start+end)/2;
if(a[mid]==num) return mid;
else if(a[mid]<num)
{
start=mid+1;
}
else
{
end=mid-1;
}
}
return -1;
}
int start=0,end=n-1;
while(start<=end)
{
int mid=(start+end)/2;
if(a[mid]==num) return mid;
else if(a[mid]<num)
{
start=mid+1;
}
else
{
end=mid-1;
}
}
return -1;
}
3)查找重复记录的第一个
int halfFind(int a[],int n,int num)//二分查找,返回重复的第一个
{
if(n<1) return -1;
int start=0,end=n-1;
int pos;
while(start<end)
{
pos=(start+end)/2;
if(a[pos]==num) end=pos;
else if(a[pos]<num) start=pos+1;
else end=pos-1;
}
if(a[start]==num) return start;
return -1;
if(n<1) return -1;
int start=0,end=n-1;
int pos;
while(start<end)
{
pos=(start+end)/2;
if(a[pos]==num) end=pos;
else if(a[pos]<num) start=pos+1;
else end=pos-1;
}
if(a[start]==num) return start;
return -1;
}
3、哈希法
见此文:http://www.cnblogs.com/yunfei181/archive/2011/07/11/2103496.html