🎉 Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io 🎉
Avatar of jaishreedhage

jaishreedhage's solution

to Binary Search in the Objective-C Track

Published at Jul 13 2018 · 0 comments
Instructions
Test suite
Solution

Implement a binary search algorithm.

Searching a sorted collection is a common task. A dictionary is a sorted list of word definitions. Given a word, one can find its definition. A telephone book is a sorted list of people's names, addresses, and telephone numbers. Knowing someone's name allows one to quickly find their telephone number and address.

If the list to be searched contains more than a few items (a dozen, say) a binary search will require far fewer comparisons than a linear search, but it imposes the requirement that the list be sorted.

In computer science, a binary search or half-interval search algorithm finds the position of a specified input value (the search "key") within an array sorted by key value.

In each step, the algorithm compares the search key value with the key value of the middle element of the array.

If the keys match, then a matching element has been found and its index, or position, is returned.

Otherwise, if the search key is less than the middle element's key, then the algorithm repeats its action on the sub-array to the left of the middle element or, if the search key is greater, on the sub-array to the right.

If the remaining array to be searched is empty, then the key cannot be found in the array and a special "not found" indication is returned.

A binary search halves the number of items to check with each iteration, so locating an item (or determining its absence) takes logarithmic time. A binary search is a dichotomic divide and conquer search algorithm.

Setup

There are two different methods of getting set up to run the tests with Objective-C:

  • Create an Xcode project with a test target which will run the tests.
  • Use the ruby gem objc as a test runner utility.

Both are described in more detail here: http://exercism.io/languages/objective-c

Submitting Exercises

When submitting an exercise, make sure your solution file is in the same directory as the test code.

The submit command will look something like:

exercism submit <path-to-exercism-workspace>/objective-c/binary-search/BinarySearch.m

You can find the Exercism workspace by running exercism debug and looking for the line beginning with Workspace.

Source

Wikipedia http://en.wikipedia.org/wiki/Binary_search_algorithm

Submitting Incomplete Solutions

It's possible to submit an incomplete solution so you can see how others have completed the exercise.

BinarySearchTest.m

#import <XCTest/XCTest.h>

#if __has_include("BinarySearchExample.h")
# import "BinarySearchExample.h"
# else
# import "BinarySearch.h"
#endif

@interface BinarySearchTest : XCTestCase

@end

@implementation BinarySearchTest

- (void)testHasListData {
    NSArray *array = @[@1, @3, @4, @6, @8, @9, @11];
    BinarySearch *binary = [[BinarySearch alloc] initWithArray:array];
    XCTAssertEqualObjects(binary.list, array);
}

- (void)testNilForUnsortedList {
    BinarySearch *binary = [[BinarySearch alloc] initWithArray:@[@2, @1, @4, @3, @6]];
    XCTAssertNil(binary);
}

- (void)testNotFoundForDataNotInList {
    BinarySearch *binary = [[BinarySearch alloc] initWithArray:@[@1, @3, @6]];
    XCTAssertEqual([binary searchFor:2], NSNotFound);
}

- (void)testFindsPositionOfMiddleItem {
    BinarySearch *binary = [[BinarySearch alloc] initWithArray:@[@1, @3, @4, @6, @8, @9, @11]];
    XCTAssertEqual(3, [binary middle]);
}

- (void)testFindsPositionOfSearchData {
    BinarySearch *binary = [[BinarySearch alloc] initWithArray:@[@1, @3, @4, @6, @8, @9, @11]];
    XCTAssertEqual(5, [binary searchFor:9]);
}

- (void)testFindsPositionInALargerList {
    BinarySearch *binary = [[BinarySearch alloc] initWithArray:@[@1, @3, @5, @8, @13, @21, @34, @55, @89, @144]];
    XCTAssertEqual(1, [binary searchFor:3]);
    XCTAssertEqual(7, [binary searchFor:55]);
}

- (void)testFindsCorrectPositionInAListWithAnEvenNumberOfElements {
    BinarySearch *binary = [[BinarySearch alloc] initWithArray:@[@1, @3, @5, @8, @13, @21, @34, @55, @89, @144, @233, @377]];
    XCTAssertEqual(5, [binary searchFor:21]);
    XCTAssertEqual(6, [binary searchFor:34]);
}

@end

BinarySearch/BinarySearchTest/BinarySearch.h

//
//  BinarySearch.h
//  BinarySearch
//
//  Created by Jaishree Dhage on 11/12/17.
//  Copyright © 2017 Jaishree Dhage. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface BinarySearch : NSObject

@property(nonatomic,strong,readonly) NSArray<NSNumber *> * list;
-(instancetype) initWithArray:(NSArray<NSNumber *> *) array;
-(NSInteger) searchFor:(NSInteger)number;
-(NSInteger) middle;

@end

BinarySearch/BinarySearchTest/BinarySearch.m

//
//  BinarySearch.m
//  BinarySearch
//
//  Created by Jaishree Dhage on 11/12/17.
//  Copyright © 2017 Jaishree Dhage. All rights reserved.
//

#import "BinarySearch.h"

@interface BinarySearch ()

@property(nonatomic,strong,readwrite) NSArray<NSNumber *> * list;

@end

@implementation BinarySearch

-(instancetype)initWithArray:(NSArray<NSNumber *> *)array{
    self = [super init];
    if(self){
        self.list = array;
        NSArray <NSNumber *> *sorted = [array sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
            return obj1>obj2;
        }];

        if(![sorted isEqualToArray:self.list])
            return nil;
    }
    return self;
}

-(NSInteger)searchFor:(NSInteger)number{
    
    if([self.list containsObject:[NSNumber numberWithInteger:number]]){
        return [self.list indexOfObject:[NSNumber numberWithInteger:number]];
    }
    return NSNotFound;
    
}

-(NSInteger)middle{
    
    NSInteger mid = ceil([self.list[[self.list count] -1] integerValue]/2.0);
    return [self.list indexOfObject:[NSNumber numberWithInteger:mid]];
}


@end

Community comments

Find this solution interesting? Ask the author a question to learn more.

What can you learn from this solution?

A huge amount can be learned from reading other people’s code. This is why we wanted to give exercism users the option of making their solutions public.

Here are some questions to help you reflect on this solution and learn the most from it.

  • What compromises have been made?
  • Are there new concepts here that you could read more about to improve your understanding?