冒泡排序

最近在整理一些基础的算法内容,冒泡排序是比较经典的排序方式,这里分别用C、OC和swift写了一下,如有不同意见,欢迎交流。

冒泡排序的基本思想是:每次比较两个相邻的元素,如果它们的顺序错误就把它们交换过来。

C语言版 

void bubble_sort( int a[],  int n); // 函数声明

int array[ 11] = { 23890127, - 95433699, - 17};

bubble_sort(array,  11); // 调用

void bubble_sort( int a[],  int n) {
     for ( int i =  0; i < n- 1; i++) { // 遍历趟数
         for ( int j =  0; j < n- 1-i; j++) { // 每趟比较的次数,这里-i是每一趟遍历完成之后都会确定一个较大数的位置 下次比较时不用再参与比较
             if (a[j] > a[j+ 1]) { // 这里是从小到大排序,大值往上冒
                 int temp = a[j];
                a[j]     = a[j+ 1];
                a[j+ 1]   = temp;
            }
        }
    }
    
    printf( " bubble_sort: ");
     for ( int i =  0; i < n; i++) {
        printf( "  %d ", a[i]);
    }
    printf( " \n ");
     // bubble_sort: -17 -9 3 7 8 12 23 36 54 90 99
}

 

OC版

_dataArray = [NSMutableArray arrayWithObjects:@ 21, @ 3, @ 34, @(- 28), @ 10, @(- 33), @ 54, @ 9, @ 0, @(- 2),  nil];

[self  bubbleSort]; // 调用

- ( void)bubbleSort {
     for ( int i =  0; i < self.dataArray.count -  1; i++) {
         for ( int j =  0; j < self.dataArray.count -  1 - i; j++) {
             if ([self.dataArray[j] integerValue] > [self.dataArray[j+ 1] integerValue]) {
                [self.dataArray exchangeObjectAtIndex:j withObjectAtIndex:(j+ 1)];
            }
        }
    }
    
    NSString * string = [self.dataArray componentsJoinedByString: @"   "];
    NSLog( @" bubbleSort : %@ "string);
     // bubbleSort : -33 -28 -2 0 3 9 10 21 34 54
}

 

swift版

var dataArray:NSMutableArray = [ 76119, - 424680, - 19];

self.bubbleSort(); // 调用

func bubbleSort() {
     for i:NSInteger  in  0 ..< dataArray.count- 1 { // 顺便说一下,这里的i标示的是下标值,不要受OC的for in所影响
         for j:NSInteger  in  0 ..< dataArray.count -  1 - i {
             if (dataArray.objectAtIndex(j).integerValue > dataArray.objectAtIndex(j+ 1).integerValue) {
                 dataArray.exchangeObjectAtIndex(j, withObjectAtIndex: j+ 1);
             }
         }
     }
        
     let  string:NSString = dataArray.componentsJoinedByString( "   ");
     NSLog( " bubble sort: %@ "string);
     // bubble sort: -19 -4 0 1 2 4 6 8 19 76
}

 

注: 排序有负数时,OC和swift对象需要转换成integerValue,swift中对象是不能比较大小的,如果不转换是不被允许进行比较的。OC比较过程中在遇到负数时,会取随机数,这样会影响排序

转载于:https://www.cnblogs.com/NINIiOS/p/5633975.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值