Skip to content

Instantly share code, notes, and snippets.

@enriquesalceda
Created November 4, 2024 22:17
Show Gist options
  • Save enriquesalceda/5e22d3d0d20fad780e68c192517ed1e6 to your computer and use it in GitHub Desktop.
Save enriquesalceda/5e22d3d0d20fad780e68c192517ed1e6 to your computer and use it in GitHub Desktop.

Challenge: Implement Binary Search

Objective:

Write a function to perform a binary search on a sorted array of integers to find the index of a given target value. If the target is not found in the array, return -1.

Requirements:

  • The function should take two inputs: a sorted array of integers and a target integer.
  • The function must use the binary search algorithm to find the target.
  • Do not use library functions or methods for the binary search; implement the algorithm manually.

Example:

Input: array = [-5, 1, 3, 7, 9, 12, 14], target = 9 Output: 4 (because array[4] = 9) Input: array = [-15, -10, -3, 0, 5, 8, 12], target = 6 Output: -1 (because 6 is not in the array)

Explanation:

Binary search involves repeatedly dividing the search interval in half. Begin with the entire array. If the value of the target is less than the value in the middle of the interval, narrow the interval to the lower half. Otherwise, narrow it to the upper half. Continue checking until the value is found or the interval is empty.

Challenge skeleton

JS

function binarySearch(array, target) {
    // Implement the binary search algorithm
    return -1;
}

// Test cases
console.log(binarySearch([-5, 1, 3, 7, 9, 12, 14], 9));  // Should return 4
console.log(binarySearch([-15, -10, -3, 0, 5, 8, 12], 6));  // Should return -1

Go

package main

import (
	"fmt"
)

func binarySearch(array []int, target int) int {
	// Implement this function
	return -1
}

func main() {
	fmt.Println(binarySearch([]int{-5, 1, 3, 7, 9, 12, 14}, 9))  // Should return 4
	fmt.Println(binarySearch([]int{-15, -10, -3, 0, 5, 8, 12}, 6))  // Should return -1
}

Python

def binary_search(array, target):
    # Implement the binary search algorithm
    pass


# Test cases
print(binary_search([-5, 1, 3, 7, 9, 12, 14], 9))  # Should return 4
print(binary_search([-15, -10, -3, 0, 5, 8, 12], 6))  # Should return -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment