Data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 7387c8f97b
commit cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions

View file

@ -0,0 +1,41 @@
#import <Foundation/Foundation.h>
@interface NSArray (BinarySearch)
// Requires all elements of this array to implement a -compare: method which
// returns a NSComparisonResult for comparison.
// Returns NSNotFound when not found
- (NSInteger) binarySearch:(id)key;
@end
@implementation NSArray (BinarySearch)
- (NSInteger) binarySearch:(id)key {
NSInteger lo = 0;
NSInteger hi = [self count] - 1;
while (lo <= hi) {
NSInteger mid = lo + (hi - lo) / 2;
id midVal = self[mid];
switch ([midVal compare:key]) {
case NSOrderedAscending:
lo = mid + 1;
break;
case NSOrderedDescending:
hi = mid - 1;
break;
case NSOrderedSame:
return mid;
}
}
return NSNotFound;
}
@end
int main()
{
@autoreleasepool {
NSArray *a = @[@1, @3, @4, @5, @6, @7, @8, @9, @10];
NSLog(@"6 is at position %d", [a binarySearch:@6]); // prints 4
}
return 0;
}

View file

@ -0,0 +1,38 @@
#import <Foundation/Foundation.h>
@interface NSArray (BinarySearchRecursive)
// Requires all elements of this array to implement a -compare: method which
// returns a NSComparisonResult for comparison.
// Returns NSNotFound when not found
- (NSInteger) binarySearch:(id)key inRange:(NSRange)range;
@end
@implementation NSArray (BinarySearchRecursive)
- (NSInteger) binarySearch:(id)key inRange:(NSRange)range {
if (range.length == 0)
return NSNotFound;
NSInteger mid = range.location + range.length / 2;
id midVal = self[mid];
switch ([midVal compare:key]) {
case NSOrderedAscending:
return [self binarySearch:key
inRange:NSMakeRange(mid + 1, NSMaxRange(range) - (mid + 1))];
case NSOrderedDescending:
return [self binarySearch:key
inRange:NSMakeRange(range.location, mid - range.location)];
default:
return mid;
}
}
@end
int main()
{
@autoreleasepool {
NSArray *a = @[@1, @3, @4, @5, @6, @7, @8, @9, @10];
NSLog(@"6 is at position %d", [a binarySearch:@6]); // prints 4
}
return 0;
}

View file

@ -0,0 +1,15 @@
#import <Foundation/Foundation.h>
int main()
{
@autoreleasepool {
NSArray *a = @[@1, @3, @4, @5, @6, @7, @8, @9, @10];
NSLog(@"6 is at position %lu", [a indexOfObject:@6
inSortedRange:NSMakeRange(0, [a count])
options:0
usingComparator:^(id x, id y){ return [x compare: y]; }]); // prints 4
}
return 0;
}

View file

@ -0,0 +1,19 @@
#import <Foundation/Foundation.h>
CFComparisonResult myComparator(const void *x, const void *y, void *context) {
return [(__bridge id)x compare:(__bridge id)y];
}
int main(int argc, const char *argv[]) {
@autoreleasepool {
NSArray *a = @[@1, @3, @4, @5, @6, @7, @8, @9, @10];
NSLog(@"6 is at position %ld", CFArrayBSearchValues((__bridge CFArrayRef)a,
CFRangeMake(0, [a count]),
(__bridge const void *)@6,
myComparator,
NULL)); // prints 4
}
return 0;
}