使用双端标记,left表示寻找最小值,right表示寻找最大值,两个指针同时移动。
package com.Sort;
import java.util.Arrays;
/**
* 优化的选择排序,使用数组两端同时都有指针
*/
public class SelectSortOpt {
public static void sort(int[] arr){
int left = 0;
int right = arr.length - 1;
while (left <= right){
int minIndex = left;
int maxIndex = right;
for(int i = left; i <= right; i ++){
if(arr[minIndex] > arr[i]){
minIndex = i;
}else if(arr[maxIndex] < arr[i]){
maxIndex = i;
}
}
if(left != minIndex){
int temp = arr[left];
arr[left] = arr[minIndex];
arr[minIndex] = temp;
}
// 最大值是起始位置时,他的索引因此会改变,即将原来的最小值的索引变换为现在的最大值
if(maxIndex == left){
maxIndex = minIndex;
}
//如果设置此代码块,需要将上述的left代码与right代码互换
// if(minIndex == right){
// minIndex = maxIndex;
// }
if(right != maxIndex){
int temp = arr[right];
arr[right] = arr[maxIndex];
arr[maxIndex] = temp;
}
left ++;
right --;
}
}
public static void main(String[] args) {
int[] arr = {9,6,3,5,4,8,2};
sort(arr);
System.out.println(Arrays.toString(arr));
}
}