About the half-lookup while condition <, <=, half-lookup while Condition
Int bin_search (int a [], int len, int key)
{
Int low = 0;
Int high = len-1;
While (low <= high) // if it is low
// The body is not executed.
{
Int mid = low + (high-low)/2;
If (a [mid] = key) return mid;
Else
If (a [mid] <key)
Low = mid + 1;
Else
High = mid-1;
}
If (low> high)
Return-1;
}
Questions about the C ++ half-fold method Lookup
// The input code has some logic problems.
// The Order is reduced by one.
// Find the missing break and
// The while LOOP condition is reversed.
# Include <iostream. h>
Void Renew (int A []);
Int BinarySearch (int A [], int x, int n );
Int main ()
{
Int Stu [15];
Int I = 0;
Int scr;
Cout <"Please enter score:" <endl;
For (I; I <15; I ++) // enter the data and check the error
{
Do
{
Cin> scr;
If (scr> = 0 & scr <= 100)
{
Stu [I] = scr;
}
Else
Cout <"incorrect input. Please enter again" <endl;
} While (scr <0 | scr> 100); // here
}
Renew (Stu); // call sorting
// Output the sorting result
For (I = 0; I <15; I ++)
{
Cout <"NewScore [" <I <"] =" <Stu [I] <endl;
}
// Call the half-way Query
Int x;
Cout <"Please enter the score in your mind:" <endl;
Cin> x;
Cout <"The Score" <x <"is the" <BinarySearch (Stu, x, 15) <endl;
Return 0;
}
Void Renew (int A []) // sorting Function
{
Int I, j, temp;
For (I = 0; I <15-1; I ++) // here
{
For (j = I + 1; j <15; j ++)
{
If (A [I] <A [j])
{
Temp = A [I];
A [I] = A [j];
A [j] = temp;
}
}
}
}
Int BinarySearch (int A [], int x, int n) // returns A half-fold query result.
{
Int left = 0;
Int right = n-1;
Int sum =-1;
Do
{
Int middle = (left + right)/2;
If (x = A [middle])
{
Sum = middle; break; // here
}
Else if (x> A [middle])
Right = middle-1;
Else left = middle + 1;
} While (left <= right); // here
Return sum;
}... Remaining full text>
What are the conditions for the end of the half-lookup method?
The loop condition is low <= high, and the ending condition is low> high.