1. 程式人生 > >將一個數組按從小到大的順序排列

將一個數組按從小到大的順序排列

在公司等開發板,只能寫寫簡單的java程式碼來補補腦。程式碼參考了java語言程式設計-基礎篇

需求:將陣列按從小到大的順序排列

不多說,直接上程式碼:

1.按照選擇排序的方法進行排序

public class SelectionSort {

    public static void main(String[] args) {

        double[] list = {1, 2.5, 3.3, 6.0, 9, 5, 7.5, 6.4};
selectionSort(list);
System.out.print("排列後的陣列為: " + "[");
        for (int 
i = 0; i < list.length - 1; i++) { System.out.print(list[i] + ", "); } System.out.println(list[list.length - 1] + "]"); } // 選擇排序 private static void selectionSort(double[] list) { for (int i = 0; i < list.length; i++) { // 尋找當前最小的值 double currentMin = list[i];
int currentMinIndex = i; for (int j = i + 1; j < list.length; j++) { if (currentMin >= list[j]) { currentMin = list[j]; currentMinIndex = j; } } if (currentMinIndex != i) { list[currentMinIndex] = list[i];
list[i] = currentMin; } } } }

2.按照插入排序的方法進行排序

public class InsertionSort {

    public static void mian(String[] args) {

        double[] list = {1, 2.5, 3.3, 6.0, 9, 5, 7.5, 6.4};
insertionSort(list);
// 列印輸出
System.out.print("排列後的數列為: " + "[");
        for (int i = 0; i < list.length - 1; i++) {
            System.out.print(list[i] + ", ");
}
        System.out.println(list[list.length - 1] + "]");
}

    // 插入排序
private static void insertionSort(double[] list) {

        for (int i = 0; i < list.length; i++) {

            double currentElement = list[i];
            int k;
            for (k = i - 1; k >= 0 && list[k] > currentElement; k--) {
                list[k + 1] = list[k];
}

            list[k + 1] = currentElement;
}

    }

}