编写程序实现选择排序java
时间: 2023-12-31 15:22:49 浏览: 29
以下是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("Sorted array:");
for (int i : arr) {
System.out.print(i + " ");
}
}
}
```
以上代码中,selectionSort方法接收一个整型数组作为参数,通过两重循环实现选择排序。外层循环遍历数组,内层循环遍历剩余部分,找到最小元素并交换位置,重复执行直到排序完成。时间复杂度为O(n^2),不适用于大规模数据排序。