Java Pencarian Biner
/*
Java Implementation of Binary Search Algorithm.
- Assuming the Array is Sorted (Ascending Order)
- returns the Index, if Element found.
- -1, if not found.
*/
public class BinarySearch {
int binarysearch(int[] array, int element) {
int a_pointer = 0;
int b_pointer = array.length -1;
if (array[a_pointer] == element) return a_pointer;
if (array[b_pointer] == element) return b_pointer;
while(a_pointer <= b_pointer){
int midpoint = a_pointer + (b_pointer - a_pointer) / 2;
if (array[midpoint] == element) return midpoint;
// ignoring the left half, if this is True.
if (array[midpoint] < element) a_pointer = midpoint + 1;
// ignoring the right half, if this is True.
else if (array[midpoint] > element) b_pointer = midpoint - 1;
}
return -1; // Element not Found
}
public static void main(String[] args) {
int[] list = {1, 2, 3, 4, 7, 9, 11, 12, 15, 19, 23, 36, 54, 87};
System.out.println(binarysearch(list, 19));
}
}
Prabhu Kiran Konda