I had the opportunity to write a 2-minute search, so I will write it as a memo.
The 2-minute search is just an algorithm that searches while narrowing down the range by half from the entire array. Fast.
Sample.java
int algorithm(int[] data, int target) {
int retrieve = -1;
int left = 0;
int right = data.length - 1;
while(left < right){
int mid = (left + right)/ 2;
if(data[mid] == target){
return mid + 1;
}else if(target < data[mid]){
return right = mid;
}else {
return left = mid + 1;
}
}
return retrieve;
}
Recommended Posts