I
import
Unregistered / Unconfirmed
GUEST, unregistred user!
二分法查找算法 // Code for BinarySearch
int BinarySearch(IntArrayType IntArray, int Low, int High, int Target)
{
int Mid, Difference;
while (Low <= High)
{
Mid = (Low + High) / 2;
Difference = IntArray[Mid] - Target;
if (Difference == 0) // IntArray[Mid] == Target
return Mid;
else if (Difference < 0) // IntArray[Mid] < Target
Low = Mid + 1;
else
High = Mid - 1;
}
return -1; // If reach here, Target was not found.
}
//////////////////////////////
Value,{ 需要查找的数据 }
L{ 数据列表最低 },H{ 数据列表最高 },M { 临时保存中间值的变量 }:integer;
ValueList:List for Sorted Data;{ 数据列表,已经排序 }
Result:=-1;
if (Value<ValueList[L]) or (Value>ValueList[H]) then exit;
while L<=H do
begin
M:=(L+H) div 2;
if ValueList[M]=Value then
begin
Result :=M;
Break;
end else if ValueList[M]>Value then
H:=M-1
else
L:=M+1;
end;
int BinarySearch(IntArrayType IntArray, int Low, int High, int Target)
{
int Mid, Difference;
while (Low <= High)
{
Mid = (Low + High) / 2;
Difference = IntArray[Mid] - Target;
if (Difference == 0) // IntArray[Mid] == Target
return Mid;
else if (Difference < 0) // IntArray[Mid] < Target
Low = Mid + 1;
else
High = Mid - 1;
}
return -1; // If reach here, Target was not found.
}
//////////////////////////////
Value,{ 需要查找的数据 }
L{ 数据列表最低 },H{ 数据列表最高 },M { 临时保存中间值的变量 }:integer;
ValueList:List for Sorted Data;{ 数据列表,已经排序 }
Result:=-1;
if (Value<ValueList[L]) or (Value>ValueList[H]) then exit;
while L<=H do
begin
M:=(L+H) div 2;
if ValueList[M]=Value then
begin
Result :=M;
Break;
end else if ValueList[M]>Value then
H:=M-1
else
L:=M+1;
end;