Java排序算法之冒泡排序

package com.xingej.algorithm.sort.bubble;

/**
 * 自定義數組類
 * 
 * 特點是:帶有冒泡排序功能
 * 
 * 冒泡排序核心:1、從數組的最後一個元素,開始比較;2、兩兩比較,滿足條件的話,就需要進行位置的互換
 * 
 * 實際生活中:小學時,需要根據身高進行座位排序,就可以使用冒泡排序進行。
 * 
 * @author erjun 2017年12月11日 上午9:20:28
 */
public class MyArrayWithBubbleSort {
    // 聲明一個數組
    private int[] arr;

    // 數組,最多能存儲多少個元素
    private int maxSize;

    // 當前數組裏,有多少個元素;有點類似於指針,索引的意思
    private int elements;

    public MyArrayWithBubbleSort(int maxSize) {
        this.maxSize = maxSize;
        arr = new int[maxSize];
        // 初始化狀態,數組裏的默認元素個數爲0
        this.elements = 0;
    }

    public void insert(int value) {
        arr[elements++] = value;
    }

    public void show() {

        for (int i = 0; i < elements; i++) {
            System.out.print(arr[i] + " ");
        }

        System.out.println();
    }

    public void bubbleSort() {
        // 4 3 2 1,按冒泡排序的話,需要進行3輪比較可以了
        for (int i = 0; i < elements - 1; i++) {
            // 每一輪比較,找出本輪的最小值
            for (int j = elements - 1; j > i; j--) {

                // 後面的/下面的水泡 小於 上面的水泡,就移位
                if (arr[j] < arr[j - 1]) {
                    swap(j, j - 1);
                }
            }
        }
    }

    // 左右值交換
    private void swap(int i, int j) {
        // java 是引用傳遞
        int temp = arr[i];
        arr[i] = arr[j];
        arr[j] = temp;
    }

}


單元測試:

package com.xingej.algorithm.sort.bubble;

import org.junit.Test;

public class MyArrayWithBubbleSortTest {

    @Test
    public void test() {
        MyArrayWithBubbleSort bubbleSort = new MyArrayWithBubbleSort(6);

        bubbleSort.insert(2);
        bubbleSort.insert(3);
        bubbleSort.insert(1);
        bubbleSort.insert(7);

        System.out.println("------排序前----打印輸出------");
        bubbleSort.show();

        bubbleSort.bubbleSort();

        System.out.println("------排序後----打印輸出------");
        bubbleSort.show();

    }

}


代碼已託管到

https://github.com/xej520/xingej-algorithm





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章