標籤:
話不多說,學了這麼多,寫個快速排序先。
除了快排,以後有時間還要加堆排、歸併等等。
今天學了有,類、協議、文法。
因為演算法類,不止一個演算法。所以建立一個Algorithm(演算法)協議:
1 #import <Foundation/Foundation.h>2 3 @protocol AlgorithmProtocol <NSObject>4 5 @optional6 +(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;}
驗證一下結果:
Objective-C學習筆記-第一天(3)