數組簡單排序

java對數組排序進行封裝Arrays.sort() 裏面進行了快速排序。手動實現一下數組的簡單排序

冒泡排序 插入排序 選擇排序

package arrays.simples.sort;

public class SimpleSort {

    /**
     * 數組冒泡排序
     */
    public static int[] bubbleSort(int[] arrays) {
        for (int i = 0; i <= arrays.length; i++) {
            boolean flag = true;
            for (int j = 0; j < arrays.length - 1; j++) {
                if (arrays[j] > arrays[j + 1]) {
                    int temp = arrays[j];
                    arrays[j] = arrays[j + 1];
                    arrays[j + 1] = temp;
                    flag = false;
                }
            }
            if (flag) { // 已順序
                break;
            }
            System.out.print("第" + (i + 1) + "輪遍歷:");
            for (int value : arrays) {
                System.out.print(value);
            }
            System.out.println();
        }
        return arrays;
    }

    /**
     * 插入排序
     */
    public static int[] insertSort(int[] arrays) {
        int insert = 0;
        for (int i = 0; i < arrays.length; i++) {
            insert = arrays[i]; // 要插入的值
            int j = 0;
            for (j = i; j > 0 && insert <= arrays[j - 1]; j--) {
                arrays[j] = arrays[j - 1];
            }
            arrays[j] = insert;
        }
        return arrays;
    }

    /**
     * 選擇排序
     */
    public static int[] selectSort(int[] arrays) {
        int minTemp = 0;  //  存儲最小值
        for (int i = 0; i < arrays.length - 1; i++) {
            for (int j = i + 1; j < arrays.length; j++) {
                if (arrays[i] > arrays[j]) {
                    minTemp = arrays[j];
                    arrays[j] = arrays[i];
                    arrays[i] = minTemp;
                }
            }
            System.out.print("第" + (i + 1) + "輪遍歷:");
            for (int value : arrays) {
                System.out.print(value);
            }
            System.out.println();
        }
        return arrays;
    }

}

測試類

package arrays;

import arrays.simples.sort.SimpleSort;

public class Test {
    
    public static void main(String[] args) {
        int[] arrays = {5, 4, 9, 6, 3, 7, 1, 8, 2};
        // 冒泡排序
        // arrays = SimpleSort.bubbleSort(arrays);
        // 選擇排序
        // arrays = SimpleSort.selectSort(arrays);
        // 插入排序
        arrays = SimpleSort.insertSort(arrays);
        for (int value : arrays) {
            System.out.print(value + " ");
        }
    }
}

 

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