BubbleSort

排序算法之冒泡排序

目录

  1. 冒泡排序介绍
  2. O(n^2)的实现方法
  3. 优化思路

1. 冒泡排序介绍

冒泡排序是一种比较简单的排序方法,以数组升序的情况为例,它的原理是从第一个元素开始,每个元素都与其相邻的元素做比较,如果前一个元素比后一个元素大,则交换两个元素的位置,每一轮排序都确定一个最大值。它是一种稳定的排序方法,因为两个元素相等时不会做交换,相对位置不会发生改变。

2. O(n^2)的实现方法

package com.zetcode;

public class BubbleSort {
    
    public static void swapFun(int[] arr, int i, int j) {
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
    
    public static void bubbleSortFun(int[] arr) {
        
        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]) {
                    
                    swapFun(arr, j, j + 1);
                }
            }
        }
    }
    
    public static void main(String[] args) {
        
        int[] my_array = new int[]{ 5, 3, 1, 6, 2, 4 };
        
        bubbleSortFun(my_array);
        
        for (int num : my_array) {

            System.out.print(num + " ");
        }
        System.out.println();
    }
}
第1趟排序结果: 3 1 5 2 4 6 
第2趟排序结果: 1 3 2 4 5 6 
第3趟排序结果: 1 2 3 4 5 6 
第4趟排序结果: 1 2 3 4 5 6 
第5趟排序结果: 1 2 3 4 5 6
package com.zetcode;

public class BubbleSort {
 
    public static void swapFun(int[] arr, int i, int j){
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }
 
    public static void bubbleSortFun(int[] arr){
        
        boolean flag;
        
        for (int i = 0; i < arr.length - 1; i++) {
            
            flag = false;
            for (int j = 0; j < arrlength - 1 - i; j++) {
                
                if(arr[j] > arr[j + 1]) {
                    
                    swap(arr, j, j + 1);
        	
                    flag = true;
                }
            }
            
            if(!flag) {
                return ;
            }
            
            System.out.print("第" + (i + 1) + "趟排序结果:");
            for (int num : arr) {
                
                System.out.print(num + " ");
            }
            System.out.println();
        }
    }
 
    public static void main(String[] args) {
        
        int[] arr = new int[] { 3, 2, 1, 5, 4, 6};
        bubbleSortFun(arr);
    }
}
//第1趟排序结果:2 1 3 4 5 6 
//第2趟排序结果:1 2 3 4 5 6 
posted @ 2020-06-05 00:49  PrimerPlus  阅读(144)  评论(0编辑  收藏  举报