java双重选择排序法
时间: 2023-11-10 07:57:07 浏览: 53
双重选择排序法(Double Selection Sort)是一种改进的选择排序算法,它在每次迭代中同时找到最小值和最大值,并分别将它们放置在已排序序列的起始和末尾。以下是使用Java实现的双重选择排序算法:
```java
public class DoubleSelectionSort {
public static void doubleSelectionSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n / 2; i++) {
int minIndex = i;
int maxIndex = i;
for (int j = i + 1; j < n - i; j++) {
if (arr[j] < arr[minIndex]) {
minIndex = j;
}
if (arr[j] > arr[maxIndex]) {
maxIndex = j;
}
}
// 将最小值交换到已排序序列的起始位置
int tempMin = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = tempMin;
// 注意:若最大值所在位置是i,交换后最大值的新位置是minIndex
if (maxIndex == i) {
maxIndex = minIndex;
}
// 将最大值交换到已排序序列的末尾位置
int tempMax = arr[n - i - 1];
arr[n - i - 1] = arr[maxIndex];
arr[maxIndex] = tempMax;
}
}
public static void main(String[] args) {
int[] arr = {64, 25, 12, 22, 11};
doubleSelectionSort(arr);
System.out.println("排序后的数组:");
for (int num : arr) {
System.out.print(num + " ");
}
}
}
```