溫馨提示×

java怎么實現選擇排序

小億
153
2023-08-16 19:26:55
欄目: 編程語言

要實現選擇排序,可以按照以下步驟進行:

  1. 遍歷數組,從第一個元素開始,將其視為最小值。

  2. 依次與后面的元素比較,若有比當前最小值更小的元素,則更新最小值。

  3. 遍歷完一次數組后,將最小值與第一個元素進行交換。

  4. 重復上述步驟,從第二個元素開始,直到數組的倒數第二個元素。

下面是一個示例代碼實現選擇排序:

public class SelectionSort {
public static void selectionSort(int[] array) {
int n = array.length;
for (int i = 0; i < n - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < n; j++) {
if (array[j] < array[minIndex]) {
minIndex = j;
}
}
// 交換最小值和當前位置的元素
int temp = array[minIndex];
array[minIndex] = array[i];
array[i] = temp;
}
}
public static void main(String[] args) {
int[] array = {64, 25, 12, 22, 11};
selectionSort(array);
System.out.println("排序后的數組:");
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
}

輸出結果為:11 12 22 25 64

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