溫馨提示×

java選擇排序法代碼如何寫

小億
118
2023-10-26 00:13:10
欄目: 編程語言

以下是使用Java編寫選擇排序算法的代碼:

public class SelectionSort {
    public static void selectionSort(int[] arr) {
        int n = arr.length;
        
        // 遍歷數組
        for (int i = 0; i < n - 1; i++) {
            // 找到未排序部分的最小元素的索引
            int minIndex = i;
            for (int j = i + 1; j < n; j++) {
                if (arr[j] < arr[minIndex]) {
                    minIndex = j;
                }
            }
            
            // 將最小元素與當前未排序部分的第一個元素交換位置
            int temp = arr[minIndex];
            arr[minIndex] = arr[i];
            arr[i] = temp;
        }
    }
    
    public static void main(String[] args) {
        int[] arr = {64, 25, 12, 22, 11};
        selectionSort(arr);
        
        System.out.println("排序后的數組:");
        for (int i : arr) {
            System.out.print(i + " ");
        }
    }
}

此代碼中的selectionSort方法使用選擇排序算法對傳入的整數數組進行排序。在每一次迭代中,它找到未排序部分的最小元素的索引,然后將其與未排序部分的第一個元素交換位置。在主方法中,我們創建了一個示例數組并調用selectionSort方法進行排序。最后,我們將排序后的數組打印出來。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女