Objective-C: Binary Search on Sorted Array
#import <Foundation/Foundation.h> // Helper function to find the index of a target value in a sorted array using binary search. // Returns the index if found, otherwise returns -1. int binarySearch(NSArray<NSNumber *> *sortedArray, NSNumber *target) { // Edge case: If the array i...
This Objective-C code implements binary search to efficiently find a target value within a sorted array of integers. It includes two versions: a concise one and a more verbose one with detailed logging for educational pu...
The `binarySearch` function implements the binary search algorithm. It repeatedly divides the search interval in half. It starts with an interval covering the whole array. If the value of the search key is less than the item in the middle of the interval, the interval is narrowed to the lower half. Otherwise, the interval is narrowed to the upper half. This process continues until the value is found or the interval is empty. The `binarySearchVerbose` function provides the same logic but with extensive `NSLog` statements to illustrate each step and decision. Edge cases like empty or nil arrays, and nil targets are handled by returning -1. The time complexity is O(log n) because the search space is halved in each iteration. The space complexity is O(1) as it uses a constant amount of extra space for variables.
function binarySearch(sortedArray, target): low = 0 high = length of sortedArray - 1 if sortedArray is nil or empty: return -1 if target is nil: return -1 while low <= high: mid = low + (high - low) / 2 midValue = sorted...