首页 > 技术文章 > 冒泡排序

TheYouth 2016-04-27 23:54 原文

1.什么是冒泡排序

答:冒泡排序是通过两个相邻的数进行比较和交换,然后把小的数放到最前面,类似于水泡,一点一点浮出水面,大的沉下去,小的浮上来,所以叫做冒泡排序。

2.代码如下

- (void)viewDidLoad {
    [super viewDidLoad];
    //Do any additional setup after loading the view, typically from a nib.
    
    //1.C语言中冒泡排序
    int a[5] = {104,22,86,90,71};
    
    bubbleScoreUsing(a,sizeof(a)/sizeof(int));
    for (int i = 0; i < sizeof(a)/sizeof(int); i++) {
        NSLog(@"%d,%ld",a[i],sizeof(a));
    }
    //2.OC中冒泡排序
    [self bubbleSort:a len:sizeof(a)/sizeof(int)];
    for (int i = 0; i < sizeof(a)/sizeof(int); i++) {
        NSLog(@"a===>%d",a[i]);
    }
    //3.给model排序
    NSMutableArray *array = [NSMutableArray array];
    for (NSInteger i = 0; i < 5; i++) {
        
        GDBModel *model = [[GDBModel alloc] init];
        model.title = [NSString stringWithFormat:@"最好的我们:%ld",100-(i+1)];
        model.userId = [NSString stringWithFormat:@"%ld",100-(i+1)];
        [array addObject:model];
    }
    [self bubbleSort:array];
    
    for (GDBModel *model in array) {
        
        NSLog(@"model =%@%@",model.userId,model.title);
    }
    
}
//1.C语言中的冒泡排序。
void bubbleScoreUsing(int a[], int len);  //函数的声明
void bubbleScoreUsing(int a[],int len ){
    for (int i = 0; i < len -1; i++) {//一共跑多少趟,最后一趟不用跑,也就是说5个数只跑4趟就可以
        for (int j = len -1; j >i; j--) {//从后往前走,相当于泡从水底冒出来到水面
            if (a[j] < a[j -1]) {
                swap(a,j,j-1);
            }
        }
    }
}
void swap (int a[],int i,int j){
    
    int temp = a[i];
    a[i]= a[j];
    a[j] = temp;
}
//2.OC中冒泡排序
- (void)bubbleSort:(int[])array len:(NSInteger)len{
    
    for (NSInteger i = 0;i < len -1; i++) {
        for (NSInteger j = len -1; j>i; j--) {
            if (array[j] < array[j - 1]) {
                NSInteger temp = array[j];
                array[j] = array[j - 1];
                array[j - 1] = temp;
            }
        }
    }
}
//3.模型排序
- (void)bubbleSort:(NSMutableArray *)array{
    for (NSUInteger i = 0; i <array.count-1; i++) {
        for (NSInteger j = array.count-1 ; j >i ; j--) {
            
            GDBModel *model = [array objectAtIndex:j];
            GDBModel *model1 = [array objectAtIndex:j-1];
            if ([model.userId compare:model1.userId options:NSCaseInsensitiveSearch] == NSOrderedAscending) {
                [array exchangeObjectAtIndex:j withObjectAtIndex:j-1];
            }
        }
    }
}

 

推荐阅读