A question made at the pang go.com programming hero Conference: Binary Search (non-recursive). Let's share it with you:
[Html]
Public class BinarySearchClass
{
Public static int binary_search (int [] array, int value)
{
Int beginIndex = 0; // low subscript
Int endIndex = array. length-1; // high subscript
Int midIndex =-1;
While (beginIndex <= endIndex ){
MidIndex = beginIndex + (endIndex-beginIndex)/2; // prevents Overflow
If (value = array [midIndex]) {
Return midIndex;
} Else if (value <array [midIndex]) {
EndIndex = midIndex-1;
} Else {
BeginIndex = midIndex + 1;
}
}
Return-1;
// If it is found, the subscript of the found value is returned. If it is not found,-1 is returned.
}
// Start prompt: the start unique identifier of the Automatic Marking. Do not delete or add it.
Public static void main (String [] args)
{
System. out. println ("Start ...");
Int [] myArray = new int [] {1, 2, 3, 5, 6, 7, 8, 9 };
System. out. println ("Search for the subscript of Number 8 :");
System. out. println (binary_search (myArray, 8 ));
}
// End // prompt: the unique identifier of the Automatic Marking end. Do not delete or add it.
}
Public class BinarySearchClass
{
Public static int binary_search (int [] array, int value)
{
Int beginIndex = 0; // low subscript
Int endIndex = array. length-1; // high subscript
Int midIndex =-1;
While (beginIndex <= endIndex ){
MidIndex = beginIndex + (endIndex-beginIndex)/2; // prevents Overflow
If (value = array [midIndex]) {
Return midIndex;
} Else if (value <array [midIndex]) {
EndIndex = midIndex-1;
} Else {
BeginIndex = midIndex + 1;
}
}
Return-1;
// If it is found, the subscript of the found value is returned. If it is not found,-1 is returned.
}
// Start prompt: the start unique identifier of the Automatic Marking. Do not delete or add it.
Public static void main (String [] args)
{
System. out. println ("Start ...");
Int [] myArray = new int [] {1, 2, 3, 5, 6, 7, 8, 9 };
System. out. println ("Search for the subscript of Number 8 :");
System. out. println (binary_search (myArray, 8 ));
}
// End // prompt: the unique identifier of the Automatic Marking end. Do not delete or add it.
}