用java语言写一个选择排序
时间: 2023-05-19 22:07:25 浏览: 57
好的,以下是用 Java 语言实现选择排序的代码:
```
public class SelectionSort {
public static void main(String[] args) {
int[] arr = {64, 25, 12, 22, 11};
int n = arr.length;
// One by one move boundary of unsorted subarray
for (int i = 0; i < n-1; i++) {
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;
// Swap the found minimum element with the first element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
// Print the sorted array
for (int i = 0; i < n; i++)
System.out.print(arr[i] + " ");
}
}
```
这段代码实现了选择排序,它的基本思想是:每次从未排序的数组中选出最小的元素,放到已排序的数组的末尾。这样,经过 n-1 次选择,就可以完成排序。