选择排序(Selection Sort)是一种简单直观的排序算法,它在每一轮中选择未排序部分中的最小(或最大)元素,并将其放置在已排序部分的末尾。以下是一个选择排序的Java代码示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
| import java.util.Arrays;
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("Original array: " + Arrays.toString(arr));
selectionSort(arr);
System.out.println("Sorted array: " + Arrays.toString(arr)); } }
|
在这个示例中,selectionSort
方法使用选择排序算法对整数数组进行排序。它从未排序部分中选择最小值,并将其与未排序部分的第一个元素交换。通过多次迭代,每次选择一个最小值,最终数组会变得有序。
尽管选择排序的时间复杂度较高(O(n^2)),但它在简单场景中具有一定的实用性。