C语言代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
|
intBinSearch(SeqList*R,intn,KeyTypeK)
{
//在有序表R[0..n-1]中进行二分查找,成功时返回结点的位置,失败时返回-1
intlow=0,high=n-1,mid;
//置当前查找区间上、下界的初值
while
(low<=high)
{
if
(R[low].key==K)
returnlow;
if
(R[high].key==k)
returnhigh;
//当前查找区间R[low..high]非空
mid=low+((high-low)/2);
//使用(low+high)/2会有整数溢出的问题
//(问题会出现在当low+high的结果大于表达式结果类型所能表示的最大值时,
//这样,产生溢出后再/2是不会产生正确结果的,而low+((high-low)/2)不存在这个问题
if
(R[mid].key==K)
returnmid;
//查找成功返回
if
(R[mid].key<K)
low=mid+1;
//继续在R[mid+1..high]中查找
else
high=mid-1;
//继续在R[low..mid-1]中查找
}
if
(low>high)
return
-1;
//当low>high时表示所查找区间内没有结果,查找失败
}
//BinSeareh
------------上面代码复杂难懂-----------------
intbsearchWithoutRecursion(intarray[],intlow,inthigh,inttarget)
{
while
(low<=high)
{
intmid=(low+high)/2;
if
(array[mid]>target)
high=mid-1;
elseif(array[mid]<target)
low=mid+1;
else
//findthetarget
returnmid;
}
//thearraydoesnotcontainthetarget
return
-1;
}
----------------------------------------
|
递归实现
1
2
3
4
5
6
7
8
9
10
11
12
13
14
intbinary_search(constintarr[],intlow,inthigh,intkey)
{
intmid=low+(high-low)/2;
if
(low>high)
return
-1;
else
{
if
(arr[mid]==key)
returnmid;
elseif(arr[mid]>key)
returnbinary_search(arr,low,mid-1,key);
else
returnbinary_search(arr,mid+1,high,key);
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
intbinary_search(constintarr[],intlow,inthigh,intkey)
{
intmid=low+(high-low)/2;
if
(low>high)
return
-1;
else
{
if
(arr[mid]==key)
returnmid;
elseif(arr[mid]>key)
returnbinary_search(arr,low,mid-1,key);
else
returnbinary_search(arr,mid+1,high,key);
}
}
|
Java代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public
static
int
binarySearch(Integer[] srcArray,
int
des) {
int
low =
0
;
int
high = srcArray.length -
1
;
while
((low <= high) && (low <= srcArray.length -
1
)
&& (high <= srcArray.length -
1
)) {
int
middle = low + ((high - low) >>
1
);
if
(des == srcArray[middle]) {
return
middle;
}
else
if
(des < srcArray[middle]) {
high = middle -
1
;
}
else
{
low = middle +
1
;
}
}
return
-
1
;
}
|