Class Examples:
/*
* Search for num in array. Return the index of the number, or
* -1 if it is not found.
*/
int search(int[] array, int num) {
for (int index = 0; index < array.length; index++) {
if (array[index] == num) {
return index;
}
}
return -1;
}
/*
* Search for num in array recursively. Return the index of the number, or
* -1 if it is not found.
*/
int recSearch(int[] array, int num, int start) {
if (start >= array.length) {
return -1;
} else if (array[start] == num) {
return start;
} else {
return recSearch(array, num, start + 1);
}
}
/*
* Binary Search for num in array. Pass in the low and high
* indices of the array for the range in which the number may
* still occur.
*/
int binarySearch(int[] array, int num, int low, int high) {
if (low > high) {
return -1;
} else {
int mid = (low + high) / 2;
if (array[mid] == num) {
// num is same as middle number
return mid;
} else if (num < array[mid]) {
// num is smaller than middle number
return binarySearch(array, num, low, mid - 1);
} else {
// num is larger than middle number
return binarySearch(array, num, mid + 1, high);
}
}
}