五、选择排序

文章目录

原理

每一次从待排序的数据元素中选出最小(或最大)的一个元素,存放在序列的起始位置,然后,再从剩余未排序元素中继续寻找最小(大)元素,然后放到已排序序列的末尾。以此类推,直到全部待排序的数据元素排完。 选择排序是不稳定的排序方法

package exercise.array;

import java.util.Arrays;

public class SelectSort {
    
    
    void selectSort(int[] arr){
    
    
        for (int i = 0; i < arr.length; i++) {
    
    
            int minIndex = findMinIndex(i,arr);
            if (minIndex == i){
    
    
                continue;
            }
            //最小的和当前的做交换
            int temp = arr[i];
            arr[i] = arr[minIndex];
            arr[minIndex] = temp;
        }
    }

    /**
     *
     * @param beginIndex 当前开始的寻找的索引
     * @param arr  数组
     * @return 返回从beginIndex开始查找,arr中最小的的数的索引
     */
    int findMinIndex (int beginIndex,int[] arr){
    
    
        int min = arr[beginIndex];
        int minIndex = beginIndex;
        for (int i = beginIndex; i <arr.length; i++) {
    
    
            if (min>arr[i]){
    
    
                min = arr[i];
                minIndex = i;
            }
        }
        return minIndex;
    }


    void print(int[] arr){
    
    
        for (int i = 0; i < arr.length; i++) {
    
    
            System.out.print(arr[i]+"\t");
        }
    }

    public static void main(String[] args) {
    
    
        int[] arr = new int[]{
    
    7,5,1,2,4,6,10};
        SelectSort selectSort = new SelectSort();
        selectSort.selectSort(arr);
        selectSort.print(arr);
    }
}

input:

7,5,1,2,4,6,10

output:

1	2	4	5	6	7	10	

猜你喜欢

转载自blog.csdn.net/aa375809600/article/details/87174396