冒泡排序

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];
            }
        }
    }
}
复制代码

 

posted @   TheYouth  阅读(258)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示