Java Reference
In-Depth Information
while ( true ) {
int mid = (start + end) / 2;
if (start == end) {
if (a [ end ] == number)
{
return end ;
}
else {
return 1;
}
if (a[mid] > = number)
{
end = mid ;
}
else {
start = mid + 1;
}
}
}
Note that the new code is missing the recursive return statements in the second part of
the code. Therefore, an if - else structure is now needed. Alternatively, the return state-
ment could have been substituted with a continue statement that goes back to the begin-
ning of the infinite while loop as shown below.
public static int binarySearch( int start , int end ,
int number ,
int [] a) {
while ( true ) {
int mid = (start + end) / 2;
if (start == end) {
if (a [ end ] == number)
{
return end ;
}
else {
return 1;
}
if (a[mid] > = number)
{
end = mid ;
continue ;
start = mid + 1;
}
}
14.4.2 Bubble Sort
Bubble sort is the easiest type of sort. You can think of boiling water. As the water
boils, the lighter particles bubble to the top, while the heavier ones sink to the bottom. The
algorithm uses the same principle. Let us examine one pass of the algorithm. Consider the
following array.
105202
The first pass of the algorithm goes left to right. It compares a pair of numbers. If they
are in the wrong order, then the algorithm swaps them. For example, the algorithm will
first look at 10 and 5. They are in the wrong order and it will swap them.
510202
 
Search WWH ::




Custom Search