二分法
#import <Foundation/Foundation.h>
@interface binarySearch : NSObject
-(NSInteger) binarySearchIndex:(NSNumber *)key arrayBySearch:(NSMutableArray *) array;
@end
#import "binarySearch.h"
@implementation binarySearch
-(NSInteger) binarySearchIndex:(NSNumber *)key arrayBySearch:(NSMutableArray *) array{
NSInteger min = 0;
NSInteger max = (NSInteger)([array count]-1);
while (min <= max) {
NSInteger mid = (min+max)/2;
if (key > [array objectAtIndex:mid]) {
min = mid + 1;
}else if (key < [array objectAtIndex:mid]){
max = mid - 1;
}else if(key == [array objectAtIndex:mid]){
return mid;
}
}
return -1;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSMutableArray *test = [[NSMutableArray alloc] init];
for (int i=0; i<20; i=i+2) {
[test addObject:[NSNumber numberWithInteger:i]];
}
binarySearch *myBinarysearch = [[binarySearch alloc] init];
NSInteger getInt = [myBinarysearch binarySearchIndex:[NSNumber numberWithInteger:100] arrayBySearch:test];
NSLog(@"%ld", (long)getInt);
}
冒泡排序
#import <Foundation/Foundation.h>
@interface bubble : NSObject
-(NSMutableArray *)bubbleSort:(NSMutableArray *)array;
@end
#import "bubble.h"
@implementation bubble
-(NSMutableArray *)bubbleSort:(NSMutableArray *)array{
for (int j=0; j<array.count; j++) {
for (int i=0; i<array.count-j-1; i++) {
if (i == [array count]-1) {
return array;
}
NSInteger pre = [[array objectAtIndex:i] intValue];
NSInteger beh = [[array objectAtIndex:i+1] intValue];
if (pre >beh) {
[array exchangeObjectAtIndex:i withObjectAtIndex:i+1];
}
}
}
return array;
}
@end
快速排序
//快速排序
-(void)quickSort:(NSMutableArray *)_dataSource startIndex:(NSInteger)start endIndex:(NSInteger)end{
if (start<end) {
NSInteger standardValue=[_dataSource[start] intValue];
NSInteger left=start,right=end;
while (start<end) {
//从后往前找,如果后面的数值大于基准值,递减
while (start<end&&[_dataSource[end] intValue]>standardValue) {
end--;
}
//小于基准值的时候,给数组中索引为start赋值
if (start<end) {
_dataSource[start]=_dataSource[end];
start=start+1;
}
//从前往后找,如果数值小于基准值,递增
while (start<end&&[_dataSource[start] intValue]<standardValue) {
start++;
}
//大于基准值,给数组中索引为end的数据赋值
if (start<end) {
_dataSource[end]=_dataSource[start];
end=end-1;
}
}
//退出的时候值start和end相等
_dataSource[start]=[NSString stringWithFormat:@"%ld",(long)standardValue];
[self quickSort:_dataSource startIndex:left endIndex:end-1];//处理左边
[self quickSort:_dataSource startIndex:end+1 endIndex:right];//处理右边
}
}