NSArray NSBinarySearchingInsertionIndex
Options for searches and insertions using indexOfObject:inSortedRange:options:usingComparator:.
enum {
NSBinarySearchingFirstEqual = (1 << 8),
NSBinarySearchingLastEqual = (1 << 9),
NSBinarySearchingInsertionIndex = (1 << 10),
};
typedef NSUInteger NSBinarySearchingOptions;
Constants
NSBinarySearchingFirstEqual
Specifies that the search should return the first object in the range that is equal to the given object.
NSBinarySearchingLastEqual
Specifies that the search should return the last object in the range that is equal to the given object.
NSBinarySearchingInsertionIndex
Returns the index at which you should insert the object in order to maintain a sorted array.
NSArray NSBinarySearchingInsertionIndex example.
NSMutableArray *array = …;
id newObject = …;
NSComparator comparator = …;
NSUInteger newIndex = [array indexOfObject:newObject
inSortedRange:(NSRange){0, [array count]}
options:NSBinarySearchingInsertionIndex
usingComparator:comparator];
[array insertObject:newObject atIndex:newIndex];
id newObject = …;
NSComparator comparator = …;
NSUInteger newIndex = [array indexOfObject:newObject
inSortedRange:(NSRange){0, [array count]}
options:NSBinarySearchingInsertionIndex
usingComparator:comparator];
[array insertObject:newObject atIndex:newIndex];
Example of [NSArray NSBinarySearchingInsertionIndex].
CGFloat targetNumber = mySlider.value;
NSUInteger index = [values indexOfObject:@(targetNumber)
inSortedRange:NSMakeRange(0, values.count)
options: NSBinarySearchingFirstEqual | NSBinarySearchingInsertionIndex
usingComparator:^(id a, id b) {
return [a compare:b];
}];
NSUInteger index = [values indexOfObject:@(targetNumber)
inSortedRange:NSMakeRange(0, values.count)
options: NSBinarySearchingFirstEqual | NSBinarySearchingInsertionIndex
usingComparator:^(id a, id b) {
return [a compare:b];
}];
NSArray NSBinarySearchingInsertionIndex example.
-(void) /*adding*/
{
int proposedIndex = 0;
proposedIndex = [array indexOfObject:node
inSortedRange:NSMakeRange(0, array.count)
options:NSBinarySearchingInsertionIndex
usingComparator:
^ NSComparisonResult(id obj1, id obj2)
{
if (obj1.valueToCompare < obj2.valueToCompare) return NSOrderedAscending;
if (obj1.valueToCompare > obj2.valueToCompare) return NSOrderedDescending;
else return NSOrderedSame;
}];
[array insertObject:node atIndex:proposedIndex];
}
{
int proposedIndex = 0;
proposedIndex = [array indexOfObject:node
inSortedRange:NSMakeRange(0, array.count)
options:NSBinarySearchingInsertionIndex
usingComparator:
^ NSComparisonResult(id obj1, id obj2)
{
if (obj1.valueToCompare < obj2.valueToCompare) return NSOrderedAscending;
if (obj1.valueToCompare > obj2.valueToCompare) return NSOrderedDescending;
else return NSOrderedSame;
}];
[array insertObject:node atIndex:proposedIndex];
}