选择排序:java选择排序代码
时间: 2024-01-21 17:15:14 浏览: 26
选择排序是一种简单直观的排序算法,它的基本思想是每次从待排序的元素中选择最小(或最大)的元素,放到已排序序列的末尾。具体的Java代码如下所示:
```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`方法中,首先通过两层循环找到未排序部分的最小元素的索引,然后将最小元素与当前位置进行交换。在`main`方法中,我们定义了一个待排序的数组,并调用`selectionSort`方法对其进行排序,最后输出排序后的结果。