共計 614 個字符,預計需要花費 2 分鐘才能閱讀完成。
以下是使用 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
方法進行排序。最后,我們將排序后的數組打印出來。
丸趣 TV 網 – 提供最優質的資源集合!
正文完