ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

Objective-C Binary Search on Sorted Array

Objective-C

Goal -- WPM

Ready
Exercise Algorithm Area
1#import <Foundation/Foundation.h>
2
3// Performs binary search on a sorted array of integers.
4// Returns the index of the target value if found, otherwise returns -1.
5NSInteger binarySearch(NSArray<NSNumber*>* sortedArray, NSInteger target) {
6// Handle empty array edge case
7if (sortedArray == nil || [sortedArray count] == 0) {
8return -1;
9}
10
11NSInteger low = 0;
12NSInteger high = [sortedArray count] - 1;
13
14// Loop while the search space is valid
15while (low <= high) {
16// Calculate mid-point to avoid potential overflow
17NSInteger mid = low + (high - low) / 2;
18NSInteger midValue = [[sortedArray objectAtIndex:mid] integerValue];
19
20// Check if target is at mid
21if (midValue == target) {
22return mid; // Target found
23}
24// If target is greater, ignore left half
25else if (midValue < target) {
26low = mid + 1;
27}
28// If target is smaller, ignore right half
29else {
30high = mid - 1;
31}
32}
33
34// Target not found in the array
35return -1;
36}
37
38int main(int argc, const char * argv[]) {
39@autoreleasepool {
40NSArray<NSNumber*>* numbers = @[@2, @5, @8, @12, @16, @23, @38, @56, @72, @91];
41
42// Test case 1: Target found in the middle
43NSInteger target1 = 23;
44NSInteger index1 = binarySearch(numbers, target1);
45NSLog(@"Array: %@, Target: %ld, Index: %ld\n", numbers, (long)target1, (long)index1);
46
47// Test case 2: Target not found
48NSInteger target2 = 45;
49NSInteger index2 = binarySearch(numbers, target2);
50NSLog(@"Array: %@, Target: %ld, Index: %ld\n", numbers, (long)target2, (long)index2);
51
52// Test case 3: Target at the beginning
53NSInteger target3 = 2;
54NSInteger index3 = binarySearch(numbers, target3);
55NSLog(@"Array: %@, Target: %ld, Index: %ld\n", numbers, (long)target3, (long)index3);
56
57// Test case 4: Target at the end
58NSInteger target4 = 91;
59NSInteger index4 = binarySearch(numbers, target4);
60NSLog(@"Array: %@, Target: %ld, Index: %ld\n", numbers, (long)target4, (long)index4);
61
62// Test case 5: Empty array
63NSArray<NSNumber*>* emptyArray = @[];
64NSInteger target5 = 10;
65NSInteger index5 = binarySearch(emptyArray, target5);
66NSLog(@"Array: %@, Target: %ld, Index: %ld\n", emptyArray, (long)target5, (long)index5);
67
68// Test case 6: Nil array
69NSInteger target6 = 10;
70NSInteger index6 = binarySearch(nil, target6);
71NSLog(@"Array: %@, Target: %ld, Index: %ld\n", nil, (long)target6, (long)index6);
72}
73return 0;
74}
Algorithm description viewbox

Objective-C Binary Search on Sorted Array

Algorithm description:

This Objective-C code implements the binary search algorithm to efficiently find a target integer within a sorted array of integers. It works by repeatedly dividing the search interval in half. If the value of the search key is less than the item in the middle of the interval, the search narrows to the lower half. Otherwise, it narrows to the upper half. This is a fundamental algorithm for searching in sorted data, commonly used in databases, search engines, and any application requiring fast lookups.

Algorithm explanation:

The `binarySearch` function takes a sorted `NSArray` of `NSNumber` objects and a target integer. It initializes `low` to 0 and `high` to the last index of the array. The core logic is a `while` loop that continues as long as `low` is less than or equal to `high`. Inside the loop, the `mid` index is calculated using `low + (high - low) / 2` to prevent potential integer overflow. The value at `mid` is compared to the `target`. If they match, `mid` is returned. If `midValue` is less than `target`, the search continues in the right half by setting `low = mid + 1`. Otherwise, the search continues in the left half by setting `high = mid - 1`. If the loop finishes without finding the target, -1 is returned. The time complexity is O(log N) because the search space is halved in each iteration. The space complexity is O(1) as it only uses a few variables. Edge cases like empty or nil arrays are handled, returning -1. The invariant is that the target, if present, must lie within the indices `low` to `high` inclusive.

Pseudocode:

FUNCTION binarySearch(sortedArray, target):
  IF sortedArray IS NULL OR sortedArray IS EMPTY THEN RETURN -1

  low = 0
  high = length(sortedArray) - 1

  WHILE low <= high:
    mid = low + (high - low) / 2
    midValue = sortedArray[mid]

    IF midValue == target THEN RETURN mid
    ELSE IF midValue < target THEN low = mid + 1
    ELSE high = mid - 1
  END WHILE

  RETURN -1
END FUNCTION