用Java写个排序选择
时间: 2024-05-03 13:23:31 浏览: 9
以下是用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[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
public static void main(String[] args) {
int[] arr = {5, 2, 6, 3, 1, 4};
selectionSort(arr);
for (int i : arr) {
System.out.print(i + " ");
}
}
}
```
在这个示例中,我们定义了一个静态方法`selectionSort`,它接受一个整数数组作为参数,并使用选择排序算法对其进行排序。该算法的基本思想是在每次迭代中找到未排序部分中的最小值,并将其放置在已排序部分的末尾。
在`main`方法中,我们创建了一个整数数组并将其传递给`selectionSort`方法进行排序。最后,我们打印出排序后的数组。