选择排序图解

选择排序

package main.com.edu.shengda.suanfa;


public class selectionSort {
    private int[] array;
    private int length;

    public selectionSort(int[] array){
        this.array = array;
        this.length = array.length;
    }

    public void display(){
        for(int a: array){
            System.out.print(a+" ");
        }
        System.out.println();
    }

    /*
     * 选择排序方法
     */


    public static void selectionSort(int[] arr) {
        /*判断数组为空或为一个元素的情况,即边界检查*/
        if (arr == null || arr.length < 2) {
            return;
        }

        /*每次要进行比较的两个数,的前面那个数的下标*/

        /*
        for (int leftindex = 0; leftindex < arr.length - 1; leftindex++) {
            //minIndex变量保存该趟比较过程中,最小元素所对应的索引,
            //先假设前面的元素为最小元素
            int minIndex = leftindex;
            //  每趟比较,将前面的元素与其后的元素逐个比较
            for (int index = leftindex + 1; index < arr.length; index++) {
                //如果后面的元素小,将后面元素的索引极为最小值的索引
                if(arr[index] < arr[minIndex]) {
                    minIndex = index;
                }
            }
            //然后交换此次查找到的最小值和原始的最小值
            swap(arr, leftindex, minIndex);
        }
        */
        //从最左边开始循环
        for (int leftindex = 0; leftindex < arr.length - 1; leftindex++) {
            //假设前面的元素为最小值
            int minIndex = leftindex;
            //从第二个开始循环
            for (int index = leftindex + 1; index < arr.length; index++) {
                //如果右边小于左边 右边就为最小值
                if (arr[index] < arr[leftindex]){
                    minIndex = index;
                }

            }
            
            int temp = arr[leftindex];
            arr[leftindex] = arr[minIndex];
            arr[minIndex] = temp;

        }



    }
/*
    public static void swap(int[] arr, int i, int j) {
        int tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }
*/




    public static void main(String[] args){
        int[] array = {38,65,97,76,13,27,49};
        InsertSort is = new InsertSort(array);
        System.out.println("排序前的数据为:");
        is.display();
        is.doInsertSort();
        System.out.println("排序后的数据为:");
        is.display();
    }
}
















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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

明月常新

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值