I tried continue & break labels in java but it throw errors.
Here is the code:
private int search(int[] seq, int key, int low, int high){
int mid = low + (high - low) / 2;
out : //label
if (key == mid) {
return mid;
}
if (key < mid) {
high = mid;
if (key != mid) {
break out;
}
}
return 1;
}
Labelled break
works only with cycles.
And beware, they are not equivalent with goto
because they transfer the control to the next statement after the break-ed cycle.
Here an example copied from the language basics tutorial - break statement on Oracle's site (I'm too lazy to be original if other good examples are available):
public static void main(String[] args) {
int[][] arrayOfInts = {
{ 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;
int i;
int j = 0;
boolean foundIt = false;
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length;j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
if (foundIt) // etc
}
}
Just in case you are interested more on how to solve the binary search than how to use break
ing to labels. The code below has the same performance as one that would use goto's (if they'd actually exist in java).
private static int search(int[] seq, int key, int low, int high) {
while (low <= high) {
// this is as good as low+(high-low)/2.
int mid = (low + high) >>> 1; // this is (low+high)/2
int midVal = seq[mid];
if (midVal < key) {
low = mid + 1;
}
else if (midVal > key) {
high = mid - 1;
}
else {
// why break when you can return?
return mid; // key found
}
}
// key not found. Return the 2's complement of the insert position:
// that is -(insertPosition+1)
return -(low + 1);
}