Words don't say much, learn so much, write a quick sort first.
In addition to the Quick platoon, there is time to add heap, merge and so on.
Learned today, classes, protocols, grammars.
Because the algorithm class, more than one algorithm. So create a new algorithm (algorithm) protocol:
1 #import <foundation/ Foundation.h>2 @protocol algorithmprotocol <nsobject>4 5 @optional 6 + (void ) Quicksortwitharray: ( nsmutablearray*) array FirstIndex: (long ) First EndIndex: (long ) End CompareMethod: (bool (^) (id , id 7 @end
Next, create a new algorithm (algorithm) class that follows the algorithm protocol:
1 #import<Foundation/Foundation.h>2 #import "AlgorithmProtocol.h"3 4 @interfaceAlgorithm:nsobject <AlgorithmProtocol>5 6 @end7 8 @implementationalgorithm9 Ten+(void) Quicksortwitharray: (nsmutablearray*) array FirstIndex: (Long) FirstIndex EndIndex: (Long) EndIndex CompareMethod: (BOOL(^) (ID,ID)) compare{ One Long(^partition) (nsmutablearray*,Long,Long) = ^ (Nsmutablearray *innerarray,LongFirstLongend) { A Longi =First ; - Longj =end; - while(i<j) { the while(I<j &&!)Compare (Innerarray[i],innerarray[j])) { -j--; - } - if(i<j) { + IDTMP =Innerarray[i]; -Innerarray[i] =Innerarray[j]; +INNERARRAY[J] =tmp; Ai++; at } - while(I<j &&!)Compare (Innerarray[i],innerarray[j])) { -i++; - } - if(i<j) { - IDTMP =Innerarray[i]; inInnerarray[i] =Innerarray[j]; -INNERARRAY[J] =tmp; toj--; + } - } the returni; * }; $ if(firstindex<EndIndex) {Panax Notoginseng LongPivot =0; -Pivot =partition (Array,firstindex,endindex); the[Self Quicksortwitharray:array firstindex:firstindex endindex:pivot-1Comparemethod:compare]; +[Self Quicksortwitharray:array firstindex:pivot+1Endindex:endindex Comparemethod:compare]; A } the } + - @end
Then it is used, the main file:
#import<Foundation/Foundation.h>#import "Algorithm.h"intMainintargcConst Char*argv[]) {@autoreleasepool {//Test ArrayNsmutablearray *array =[[Nsmutablearray alloc] init]; [Array addobject:@ A]; [Array addobject:@2]; [Array addobject:@ -]; [Array addobject:@4]; [Array addobject:@ Wu]; Nsmutablearray*arraycopy =[array copy]; [Algorithm Quicksortwitharray:array FirstIndex:0Endindex:[array Count]-1comparemethod:^BOOL(IDObj1,IDobj2) { if(obj1>obj2) { return true; }Else{ return false; } }]; NSLog (@"\ n Sort before:%@\n after sorting:%@", Arraycopy,array); } return 0;}
Verify the results:
OBJECTIVE-C study notes-First day (3)