Objective-C学习笔记-第一天(3)

话不多说,学了这么多,写个快速排序先。

除了快排,以后有时间还要加堆排、归并等等。

今天学了有,类、协议、语法。

因为算法类,不止一个算法。所以新建一个Algorithm(算法)协议:

 #import <Foundation/Foundation.h>

 @protocol AlgorithmProtocol <NSObject>

 @optional
+(void)quickSortWithArray:(NSMutableArray*)array FirstIndex:(long)first EndIndex:(long)end CompareMethod:(bool(^)(id,id)) compare; @end

接下来,新建一个Algorithm(算法)类,遵循算法协议:

 #import <Foundation/Foundation.h>
#import "AlgorithmProtocol.h" @interface Algorithm : NSObject <AlgorithmProtocol> @end @implementation Algorithm +(void)quickSortWithArray:(NSMutableArray*)array FirstIndex:(long)firstIndex EndIndex:(long)endIndex CompareMethod:(bool(^)(id,id)) compare{
long (^partition)(NSMutableArray*,long,long) = ^(NSMutableArray *innerArray,long first,long end){
long i = first;
long j = end;
while (i<j) {
while (i<j && !compare(innerArray[i],innerArray[j])) {
j--;
}
if (i<j) {
id tmp = innerArray[i];
innerArray[i] = innerArray[j];
innerArray[j] = tmp;
i++;
}
while (i<j && !compare(innerArray[i],innerArray[j])) {
i++;
}
if (i<j) {
id tmp = innerArray[i];
innerArray[i] = innerArray[j];
innerArray[j] = tmp;
j--;
}
}
return i;
};
if (firstIndex<endIndex) {
long pivot = ;
pivot = partition(array,firstIndex,endIndex);
[self quickSortWithArray:array FirstIndex:firstIndex EndIndex:pivot- CompareMethod:compare];
[self quickSortWithArray:array FirstIndex:pivot+ EndIndex:endIndex CompareMethod:compare];
}
} @end

然后就是使用,main文件:

#import <Foundation/Foundation.h>
#import "Algorithm.h" int main(int argc, const char * argv[]) {
@autoreleasepool {
//测试数组
NSMutableArray *array = [[NSMutableArray alloc] init];
[array addObject:@];
[array addObject:@];
[array addObject:@];
[array addObject:@];
[array addObject:@];
NSMutableArray *arrayCopy = [array copy]; [Algorithm quickSortWithArray:array FirstIndex: EndIndex:[array count] - CompareMethod:^bool(id obj1, id obj2) {
if (obj1>obj2){
return true;
}else{
return false;
}
}]; NSLog(@"\n排序前:%@\n排序后:%@",arrayCopy,array);
}
return ;
}

验证一下结果:

Objective-C学习笔记-第一天(3)

上一篇:机器学习 —— 概率图模型(学习:CRF与MRF)


下一篇:svn post-commit 同步