冒泡排序

50 阅读1分钟

思路:把第一个数和第二个数比较,大于就换位置。然后第二个数和第三个数比较。最后越大的数就会被放在越后面。

再来n-1个循环,从能从小到大排序成功了。

package sort;

import java.util.Arrays;

public class MaoPao {
    public static void main(String[] args) {
        int a[] = new int[10];
        for (int i = 0; i < a.length; i++) {
            a[i] = (int)(Math.random() * 10);
        }

        System.out.println(Arrays.toString(a));

        System.out.println(Arrays.toString(Bubble(a)));
    }

    public static int[] Bubble(int b[]){
        for (int i = 0; i < b.length - 1; i++) {
            for (int j = 0; j < b.length - 1 - i; j++){
                if (b[j] > b[j + 1]){
                    int temp = b[j];
                    b[j] = b[j + 1];
                    b[j + 1] = temp;
                }
            }
        }
        return b;
    }
}