import java.util.Arrays;
// Abstract class defining the template method
abstract class MySearch {
// Template method defining the overall process
public final int binarySearch(int[] arr, int value) {
sort(arr);
return find(arr, value);
}
// Abstract methods to be implemented by subclasses
abstract void sort(int[] arr);
private int find(int[] arr, int value) {
int left = 0;
int right = arr.length - 1;
while (left <= right){
int mid = (left + right)/2;
if(arr[mid] == value){
return mid;
}
else if(arr[mid] < value){
left = mid + 1;
}
else{
right = mid - 1;
}
}
return -1;
}
}
// Concrete subclass for making tea
class pubbleSortSearch extends MySearch {
@Override
void sort(int[] arr) {
for(int i = 0; i < arr.length; i++){
for(int j = 0; j < arr.length - i -1; j++){
if(arr[j] > arr[j+1]){
int tmp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = tmp;
}
}
}
}
// Implementing abstract methods
}
// Concrete subclass for making coffee
class rapidSortSearch extends MySearch {
@Override
void sort(int[] arr) {
Arrays.sort(arr);
}
// Implementing abstract methods
}
public class Main {
public static void main(String[] args) {
int[] arr = {1,2,3,4,5,6,12,45,56,77,123,222};
System.out.println("pubbleSortSearch:");
MySearch mySearch = new pubbleSortSearch();
int index = mySearch.binarySearch(arr, 123);
System.out.println(index);
System.out.println("rapidSortSearch:");
mySearch = new rapidSortSearch();
index = mySearch.binarySearch(arr, 123);
System.out.println(index);
}
}
07-15
1012
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
03-17
2613
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)