简单选择排序

package lbs;
import java.util.Arrays;

//简单选择排序
public class Num6 {
    public static void main(String[] args) {
        int[] a = { 10, 7, 3, 5, 9, 1, 6, 8, 2, 4 };
        System.out.println("排序前:" + Arrays.toString(a));
        Num6 simpleSelectSort = new Num6();
        simpleSelectSort.selectionSort(a);
        System.out.println("简单选择排序后:" + Arrays.toString(a));
    }
    public void selectionSort(int[] arr) {
        for (int i = 0; i < arr.length-1; i++) {
            int min = i;
            for (int j = i+1; j<arr.length; j++) {
                if(arr[j] < arr[min]) {
                    min = j;
                }
            }
            if(min!=i) {
                //System.out.println(arr[i]+"and"+arr[min]);
                //swap(arr[i],arr[min]);
                swap(arr,i,min);
                //System.out.println(arr[i]+"and"+arr[min]);
            }
        }
    }
    //原生数据类型是直接赋值,无法实现交换:https://blog.csdn.net/qbg291932598/article/details/69055864
    /*public void swap (int a, int b) {
        int temp = a;
        a = b;
        b = temp;
    }*/
    public void swap (int[] arr, int a, int b) {
        int temp = arr[a];
        arr[a] = arr[b];
        arr[b] = temp;
    }
}
/*
 * 第二种方法
package lbs;
import java.util.Arrays;

//简单选择排序
public class Num6 {
    public static void main(String[] args) {
        int[] a = { 10, 7, 3, 5, 9, 1, 6, 8, 2, 4 };
        System.out.println("排序前:" + Arrays.toString(a));
        Num6 simpleSelectSort = new Num6();
        simpleSelectSort.selectionSort(a);
        System.out.println("简单选择排序后:" + Arrays.toString(a));
    }
    public void selectionSort(int[] arr) {
        // 需要遍历获得最小值的次数
        // 要注意一点,当要排序 N 个数,已经经过 N-1 次遍历后,已经是有序数列
        for (int i = 0; i < arr.length - 1; i++) {
            int min = i; // 用来保存最小值得索引
            // 寻找第i个小的数值
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[min] > arr[j])
                    min = j;
            }
            // 若min有变化,就将找到的第i个小的数值与第i个位置上的数值交换
            if (min != i) {
                int temp = arr[min];
                arr[min] = arr[i];
                arr[i] = temp;
            }
        }
    }
}
*/

 

posted @ 2022-03-20 17:46  tobeachallenger  阅读(29)  评论(0)    收藏  举报