ðŸŽ‰ Exercism Research is now launched. Help Exercism, help science and have some fun at research.exercism.io ðŸŽ‰

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.

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

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.

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

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

```
#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
```

```
#import <Foundation/Foundation.h>
@interface BinarySearch : NSObject
@property (nonatomic, strong) NSArray *list;
@property (nonatomic, assign) NSInteger middle;
- (instancetype)initWithArray:(NSArray *)array;
- (NSInteger)searchFor:(NSInteger)number;
@end
```

```
#import "BinarySearch.h"
@implementation BinarySearch
- (instancetype)initWithArray:(NSArray *)array {
NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(NSNumber *obj1, NSNumber *obj2) {
return [obj1 integerValue] > [obj2 integerValue];
}];
if (![array isEqualToArray:sortedArray]) {
return nil;
}
if (self = [super init]) {
self.list = array;
self.middle = array.count / 2;
}
return self;
}
- (NSInteger)searchFor:(NSInteger)number {
NSInteger middle = self.list.count / 2;
NSInteger middleValue = [self.list[middle] integerValue];
NSArray *subarray = self.list;
do {
if (number == middleValue) {
return [self.list indexOfObject:subarray[middle]];
}
if (middle == 0) {
return NSNotFound;
}
if (number > middleValue) {
subarray = [subarray subarrayWithRange:NSMakeRange(middle + 1, subarray.count % 2 == 0 ? middle - 1 : middle)];
} else {
subarray = [subarray subarrayWithRange:NSMakeRange(0, middle)];
}
middle = subarray.count / 2;
middleValue = [subarray[middle] integerValue];
} while (YES);
return NSNotFound;
}
@end
```

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?

Level up your programming skills with 3,450 exercises across 52 languages, and insightful discussion with our volunteer team of welcoming mentors.
Exercism is
**100% free forever**.

## Community comments