選擇排序(Selection Sort)是一種簡單直觀的排序算法。它的基本思想是:每次從未排序的部分中選擇最?。ɑ蜃畲螅┑脑?,將其放到已排序部分的末尾。選擇排序的時間復雜度為O(n2),因此它適用于數據量較小的場景。
下面是一個使用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};
System.out.println("排序前的數組:");
printArray(arr);
selectionSort(arr);
System.out.println("排序后的數組:");
printArray(arr);
}
public static void printArray(int[] arr) {
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println();
}
}
selectionSort方法:
n
是數組的長度。main方法:
arr
。selectionSort
方法對數組進行排序。printArray
方法打印排序前后的數組。運行上述代碼,輸出結果如下:
排序前的數組:
64 25 12 22 11
排序后的數組:
11 12 22 25 64
選擇排序是一種基礎的排序算法,雖然它的時間復雜度較高,但在某些特定場景下(如數據量較小或對內存要求較高)仍然有其應用價值。通過本文的示例代碼,你可以輕松地在Java中實現選擇排序,并理解其工作原理。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。