Share & grow the world's code base!

Delve into a community where programmers unite to discover code snippets, exchange skills, and enhance their programming proficiency. With abundant resources and a supportive community, you'll find everything essential for your growth and success.

3 snippets
  • Binary search algorithm in PHP

    <?php 
      
    function binarySearch(array $arr, int $target): int 
    { 
        $low = 0; 
        $high = count($arr) - 1; 
          
        while ($low <= $high) {          
            // compute middle index 
            $mid = floor(($low + $high) / 2);  
      
            if ($arr[$mid] > $target) { 
                // search the left side of the array 
                $high = $mid -1; 
            } else if ($arr[$mid] < $target) { 
                // search the right side of the array 
                $low = $mid + 1; 
            } else {
                // element found at mid 
                return $mid; 
            }
        } 
          
        // If we reach here element x doesnt exist 
        return -1; 
    } 
      
    // Driver code 
    $arr = [1, 2, 3, 4, 5]; 
    $target = 3;
    $result = binarySearch($arr, $target);
    
    if($result !== -1) { 
        echo "Target '$target' exists at position $result"; 
    } else {
        echo "Target '$target' does not exist";
    }

    Double search is a search method used to find an element in a sorted array.

  • Binary search algorithm in Python

    # Returns index of target in arr if present, else -1
    def binary_search(arr, target):
    	low = 0
    	high = len(arr) - 1
    
    	while low <= high:
    		# Check base case
    		mid = (high + low) // 2
    
    		# If element is smaller than mid, then it can only
    		# be present in left subarray
    		if arr[mid] > target:
    			high = mid - 1
    		# Else the element can only be present in right subarray
    		elif arr[mid] < target:
    			low = mid + 1
    		# If element is present at the middle itself
    		else:
    			return mid
    
    	# Element is not present in the array
    	return -1
    
    # Test array
    arr = [ 2, 3, 4, 10, 40 ]
    target = 10
    
    result = binary_search(arr, target)
    
    if result != -1:
    	print("Element is present at index", str(result))
    else:
    	print("Element is not present in array")

    Binary Search is a searching algorithm for finding an element's position in a sorted array. In this approach, the element is always searched in the middle of a portion of an array.

  • Binary search algorithm in Go

    package main
    
    import "fmt"
    
    // return target index if it exists in arr
    func search(arr []int, target int) int {
        low := 0
        high := len(arr) - 1
    
        for low <= high {
            mid := (low + high) / 2
    
            if arr[mid] < target {
                low = mid + 1
            } else if arr[mid] > target {
                high = mid - 1
            } else {
                return mid
            }
        }
    
        return -1
    }
    
    func main() {
        target := 7
        items := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
        fmt.Printf("Element '%d' index is %d", target, search(items, target))
    }
    
    // $ output
    // 6

    The binary search algorithm employs a divide-and-conquer approach to locate an item within a sorted array or list. It begins by comparing the target value to the middle element of the array. If they are not identical, the algorithm eliminates the half of the array where the target cannot reside and proceeds the search on the remaining half. This process iterates, with each step narrowing down the search range until the target value is discovered. If the search concludes with an empty remaining half, it indicates that the target is not present in the array.