用Java编写选择排序
时间: 2024-05-11 10:14:18 浏览: 6
以下是使用Java编写选择排序的示例代码:
```java
public class SelectionSort {
public static void main(String[] args) {
int[] arr = {64, 25, 12, 22, 11};
int n = arr.length;
selectionSort(arr, n);
System.out.println("排序后的数组:");
for (int i = 0; i < n; i++) {
System.out.print(arr[i] + " ");
}
}
public static void selectionSort(int[] arr, int n) {
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;
}
}
}
```
在上面的示例中,我们定义了一个名为`selectionSort`的静态方法,它接受一个整数数组和一个整数`n`作为参数。该方法使用选择排序算法对数组进行排序。
在`selectionSort`方法中,我们使用两个嵌套的循环。外部循环从数组的第一个元素开始,直到倒数第二个元素。内部循环从外部循环的下一个元素开始,直到数组的最后一个元素。在内部循环中,我们找到最小值的索引,并在外部循环中将其与当前元素交换。
最后,我们在`main`方法中声明一个整数数组,并将其传递给`selectionSort`方法进行排序。然后,我们遍历排序后的数组,并在控制台上打印每个元素。