Answers for "binary search,"

1

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")
Posted by: Guest on February-16-2022
4

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));
    }
}
Posted by: Guest on January-09-2022
0

Binary Search

10 101 61 126 217 2876 6127 39162 98126 712687 1000000000100 6127 1 61 200 -10000 1 217 10000 1000000000
Posted by: Guest on August-06-2021

Python Answers by Framework

Browse Popular Code Answers by Language