Binary Search Algorithm
/*
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));
}
}
Binary Search
const numbers = [1, 2, 3,4,5,6,7,8,9,10];
function binarySearch(sortedArray, key){
let start = 0;
let end = sortedArray.length - 1;
while (start <= end) {
let middle = Math.floor((start + end) / 2);
console.log(middle)
if (sortedArray[middle] === key) {
// found the key
return middle;
} else if (sortedArray[middle] < key) {
// continue searching to the right
start = middle + 1;
} else {
// search searching to the left
end = middle - 1;
}
}
// key wasn't found
return -1;
}
console.log(binarySearch(numbers,4))
Binary Search
10 101 61 126 217 2876 6127 39162 98126 712687 1000000000100 6127 1 61 200 -10000 1 217 10000 1000000000
binary search
function binarySearchRicorsivo(array A, int p, int r, int v)
if p > r
return -1
if v < A[p] or v > A[r]
return -1
q= (p+r)/2
if A[q] == v
return q
else if A[q] > v
return binarySearchRicorsivo(A,p,q-1,v)
else
Binary Search
class BinarySearchExample{
public static void binarySearch(int arr[], int first, int last, int key){
int mid = (first + last)/2;
while( first <= last ){
if ( arr[mid] < key ){
first = mid + 1;
}else if ( arr[mid] == key ){
System.out.println("Element is found at index: " + mid);
break;
}else{
last = mid - 1;
}
mid = (first + last)/2;
}
if ( first > last ){
System.out.println("Element is not found!");
}
}
public static void main(String args[]){
int arr[] = {10,20,30,40,50};
int key = 50;
int last=arr.length-1;
binarySearch(arr,0,last,key);
}
}
Binary Search
def binary_search(arr, x):
low = 0
high = len(arr) - 1
mid = 0
while low <= high:
mid = (high + low) // 2
// If x is greater, ignore left half
if arr[mid] < x:
low = mid + 1
// If x is smaller, ignore right half
elif arr[mid] > x:
high = mid - 1
// means x is present at mid
else:
return mid
// If we reach here, then the element was not present
return -1
// Test array
arr = [ 2, 3, 4, 10, 40 ]
x = 10
// Function call
result = binary_search(arr, x)
if result != -1:
print("Element is present at index", str(result))
else:
print("Element is not present in array")
|