选择排序图解

选择排序

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();
    }
}
















猜你喜欢

转载自blog.csdn.net/weixin_45905210/article/details/121384946
今日推荐