Skip to content

Instantly share code, notes, and snippets.

@keitaito
Last active September 10, 2015 07:22
Show Gist options
  • Save keitaito/fddf5acc6a8d2c94295e to your computer and use it in GitHub Desktop.
Save keitaito/fddf5acc6a8d2c94295e to your computer and use it in GitHub Desktop.
BinarySearch.m
//
// BinarySearch.m
// KIObjcAlgorithms
//
// Created by Keita on 9/8/15.
// Copyright (c) 2015 Keita Ito. All rights reserved.
//
#import "BinarySearch.h"
@implementation BinarySearch
- (NSInteger)binarySearch:(NSArray *)array targetNumber:(NSUInteger)target {
NSUInteger minIndex = 0;
NSUInteger maxIndex = array.count - 1;
NSUInteger midIndex = 0;
while (minIndex <= maxIndex) {
NSLog(@"minIndex: %ld (%@) maxIndex: %ld (%@)", minIndex, array[minIndex], maxIndex, array[maxIndex]);
midIndex = (minIndex + maxIndex) / 2;
NSLog(@"midIndex is now %ld (%@)", midIndex, array[midIndex]);
if ([[array objectAtIndex:midIndex] integerValue] == target) {
NSLog(@"target index is %ld", midIndex);
return midIndex;
}
else if ([[array objectAtIndex:midIndex] integerValue] < target) {
minIndex = midIndex + 1;
}
else if ([[array objectAtIndex:midIndex] integerValue] > target) {
maxIndex = midIndex - 1;
}
}
NSLog(@"Target is not found");
return -1;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment