优化后的选择排序

使用双端标记,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));
    }
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值