Java实现八大排序中的冒泡排序(牢记)

package com.fastech;

import java.util.Arrays;

public class BubbleSort {

    public static void main(String[] args) {
        // {65,21,34,78,90,121,23,43,12}
        // -> {21,34,65,78,90,23,43,12,121}
        // -> {21,34,65,78,23,43,12,90,121}
        // -> {21,34,65,23,43,12,78,90,121}
        // -> {21,34,23,43,12,65,78,90,121}
        // -> {21,23,34,12,43,65,78,90,121}
        // -> {21,23,12,34,43,65,78,90,121}
        // -> {21,12,23,34,43,65,78,90,121}
        // -> {21,12,23,34,43,65,78,90,121}
        // -> {12,21,23,34,43,65,78,90,121}
//        int[] arr = new int[]{65,21,34,78,90,121,23,43,12};
        // {12,21,34,78,90,121,23,43,65}
        // -> {12,21,34,78,90,23,43,65,121}
        // -> {12,21,34,78,23,43,65,90,121}
        // -> {12,21,34,23,43,65,78,90,121}
        // -> {12,21,23,34,43,65,78,90,121}
        // -> {12,21,23,34,43,65,78,90,121} 校验一次
        int[] arr = new int[]{12,21,34,78,90,121,23,43,65};
        System.out.println(Arrays.toString(arr));
        bubbleSortPlus(arr);
        System.out.println(Arrays.toString(arr));
    }

    private static void bubbleSort(int[] arr) {
        int temp;
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j+1]) {
                    temp = arr[j+1];
                    arr[j+1] = arr[j];
                    arr[j] = temp;
                }
            }
        }
    }

    private static void bubbleSortPlus(int[] arr) {
        int temp;
        for (int i = 0; i < arr.length - 1; i++) {
            boolean flag = false;
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j+1]) {
                    temp = arr[j+1];
                    arr[j+1] = arr[j];
                    arr[j] = temp;
                    flag = true;
                }
            }
            if (!flag) {
                break;
            }
        }
    }

}

你可能感兴趣的:(java,算法,排序算法)