使用java语句实现选择排序
时间: 2023-12-31 14:11:27 浏览: 27
选择排序是一种简单的排序算法,它的基本思想是每次从未排序的元素中选出最小的元素,然后放到已排序的末尾。下面是使用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 = {64, 25, 12, 22, 11};
selectionSort(arr);
System.out.println("Sorted array:");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
```
上述代码中,selectionSort()方法接受一个整型数组作为参数,使用嵌套的for循环遍历数组,每次找到未排序元素中的最小值,并将它和当前位置的元素交换。在main()方法中,我们创建一个包含5个元素的整型数组,调用selectionSort()方法对数组进行排序,并输出排序后的结果。