码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-06-10 17:47:09      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

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

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

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

因为算法类,不止一个算法。所以新建一个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;
}

验证一下结果:

技术分享

 

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

标签:

原文地址:http://www.cnblogs.com/kptanjunhao/p/5573908.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!