数据结构--冒泡排序

OC和C方法混合版冒泡排序

//
//  main.m
//
//
//  Created by hhg on 15-6-15.
//  Copyright (c) 2015年 hhg. All rights reserved.
//

#import <Foundation/Foundation.h>

void sortArr(NSMutableArray *arrM) {
    for (NSInteger i = 0; i < arrM.count - 1; i++) {
        for (NSInteger j = 0; j < arrM.count - 1 - i; j++) {
            if (arrM[j] >  arrM[j+1]) {
                [arrM exchangeObjectAtIndex:j withObjectAtIndex:j+1];
            }
        }
    }
}

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSMutableArray * arr = [[NSMutableArray alloc]initWithObjects:@4324,@4,@45,@76,@6546, nil];
        NSLog(@"排序前 = %@",arr);
        sortArr(arr);
        NSLog(@"排序后 = %@",arr);
    }
    return 0;
}

OC版冒泡排序

//
//  ViewController.m
//
//
//  Created by hhg on 15-6-15.
//  Copyright (c) 2015年 hhg. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSMutableArray *arr = [[NSMutableArray alloc]initWithObjects:@12,@3,@54,@56, nil];
    NSLog(@"排序前 = %@", arr);
    [self sortArr:arr];
    NSLog(@"排序后 = %@", arr);

}

/// 冒泡排序
- (void)sortArr:(NSMutableArray *)arrM  {
    for (NSInteger i = 0; i < arrM.count - 1; i++) {
        for (NSInteger j = 0; j < arrM.count - 1 - i; j++) {

            if (arrM[j]  > arrM[j+1] ) {
                [arrM exchangeObjectAtIndex:j withObjectAtIndex:j+1];
            }
        }
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
@end

猜你喜欢

转载自blog.csdn.net/csdn_hhg/article/details/80490767