程序员

冒泡排序(java/oc/python/scala)

2017-06-16  本文已影响0人  狼牙战士

冒泡排序就是把小的元素往前调或者把大的元素往后调。比较是相邻的两个元素比较,交换也发生在这两个元素之间。时间复杂度为 O(n^2)。
点击查看冒泡排序原理动画演示

java代码:

import java.util.Arrays;

public class MyClass {
    public static void main(String[] args){
        int[] array = {9,35,4,78,31,2,777,56,83,15};
        int[] arr1=sort(array);
        System.out.println(Arrays.toString(arr1));
    }
    public static int[] sort(int[] array){
        int[] arr = array;
        for(int i = 0;i<arr.length;i++){
            for(int j = 0;j<arr.length-i-1;j++){
                if(arr[j]>arr[j+1]){
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        return arr;
    }

}

oc代码:

#import "ViewController.h"

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    NSMutableArray *array = [NSMutableArray arrayWithObjects:@9,@35,@4,@78,@31,@2,@777,@56,@83,@15, nil];
    [self sort:array];
}

-(void)sort:(NSMutableArray*)arr{
    for(int i = 0;i<[arr count];i++){
        for(int j = 0;j<[arr count]-i-1;j++){
            if(arr[j]>arr[j+1]){
                [arr exchangeObjectAtIndex:j withObjectAtIndex:j+1];
            }
        }
    }
    for(int i = 0;i<[arr count];i++){
        NSLog(@"%d",[arr[i] intValue]);
    }
}

@end

python代码:

def paixu(array):
    #控制外层循环
    for i in range(0,len(array)):
        #内层循环
        for j in range(0,len(array)-i-1):
            #把大数放到后面
            if array[j]>array[j+1]:
                array[j],array[j+1] = array[j+1],array[j]
    print(array)

if __name__ == "__main__":
    array = [9,35,4,78,31,2,777,56,83,15]
    paixu(array)

scala代码:

object HelloWorld {
    def main(args:Array[String]){
        var array = Array(9,35,4,78,31,2,777,56,83,15)
        sort(array)
    }

    def sort(array:Array[Int]):Unit={
        for(i <- 0 to array.length-1){
            for(j <- 0 to array.length-i-2){
                if(array(j)>array(j+1)){
                    var temp:Int = array(j)
                    array(j) = array(j+1)
                    array(j+1) = temp
                }
            }
        }
        for ( x <- array ) {
         println( x )
      }
    }
}

结果:

Snip20170616_2.png
上一篇下一篇

猜你喜欢

热点阅读