话不多说,学了这么多,写个快速排序先。
除了快排,以后有时间还要加堆排、归并等等。
今天学了有,类、协议、语法。
因为算法类,不止一个算法。所以新建一个Algorithm(算法)协议:
1 #import <Foundation/Foundation.h> 2 3 @protocol AlgorithmProtocol <NSObject> 4 5 @optional 6 +(void)quickSortWithArray:(NSMutableArray*)array FirstIndex:(long)first EndIndex:(long)end CompareMethod:(bool(^)(id,id)) compare; 7 8 @end
接下来,新建一个Algorithm(算法)类,遵循算法协议:
1 #import <Foundation/Foundation.h> 2 #import "AlgorithmProtocol.h" 3 4 @interface Algorithm : NSObject <AlgorithmProtocol> 5 6 @end 7 8 @implementation Algorithm 9 10 +(void)quickSortWithArray:(NSMutableArray*)array FirstIndex:(long)firstIndex EndIndex:(long)endIndex CompareMethod:(bool(^)(id,id)) compare{ 11 long (^partition)(NSMutableArray*,long,long) = ^(NSMutableArray *innerArray,long first,long end){ 12 long i = first; 13 long j = end; 14 while (i<j) { 15 while (i<j && !compare(innerArray[i],innerArray[j])) { 16 j--; 17 } 18 if (i<j) { 19 id tmp = innerArray[i]; 20 innerArray[i] = innerArray[j]; 21 innerArray[j] = tmp; 22 i++; 23 } 24 while (i<j && !compare(innerArray[i],innerArray[j])) { 25 i++; 26 } 27 if (i<j) { 28 id tmp = innerArray[i]; 29 innerArray[i] = innerArray[j]; 30 innerArray[j] = tmp; 31 j--; 32 } 33 } 34 return i; 35 }; 36 if (firstIndex<endIndex) { 37 long pivot = 0; 38 pivot = partition(array,firstIndex,endIndex); 39 [self quickSortWithArray:array FirstIndex:firstIndex EndIndex:pivot-1 CompareMethod:compare]; 40 [self quickSortWithArray:array FirstIndex:pivot+1 EndIndex:endIndex CompareMethod:compare]; 41 } 42 } 43 44 @end
然后就是使用,main文件:
#import <Foundation/Foundation.h> #import "Algorithm.h" int main(int argc, const char * argv[]) { @autoreleasepool { //测试数组 NSMutableArray *array = [[NSMutableArray alloc] init]; [array addObject:@12]; [array addObject:@2]; [array addObject:@33]; [array addObject:@4]; [array addObject:@54]; NSMutableArray *arrayCopy = [array copy]; [Algorithm quickSortWithArray:array FirstIndex:0 EndIndex:[array count] - 1 CompareMethod:^bool(id obj1, id obj2) { if (obj1>obj2){ return true; }else{ return false; } }]; NSLog(@"\n排序前:%@\n排序后:%@",arrayCopy,array); } return 0; }
验证一下结果:
时间: 2024-10-19 00:37:50