选择排序

直接选择排序(不能有重复的值)不稳定

代码:

 public static void main(String[] args) {
        int[] array = {3, 1,3, 4, 80, 64, 65, 246, 5, 156, 456, 2, 56};
        showArray(array);
        int index;
        for (int i = 1; i < array.length; i++) {
            index = 0;
            for (int j = 0; j < array.length - i; j++) {
                if (array[j] > array[index]) {
                    index = j;
                }
            }
            int temp = array[array.length - i];// 把最后一位元素值保持到临时变量中
            array[array.length - i] = array[index];// 把最大值值保存到最后一位元素单元中
            array[index] = temp;// 把最后一位原值保存到最大值所在元素中
        }
        System.out.println();
        showArray(array);
    }

    public static void showArray(int[] array) {
        for (int i : array) {
            System.out.print(i + "  ");
        }
    }
View Code

 自然选择

public static void main(String[] args) {
        int[]arr={1,5,3,8,12,7,23,18,15};
        System.out.println("排序前的数组顺序:");
        showArray(arr);
        System.out.println();
        //自然选择排序
        for(int i=0;i<arr.length-1;i++)
        {
            int flag=i;//假设第flag个元素即为最小值,下面遍历,遇到更小的就更新
            for(int j=i;j<arr.length;j++)
            {
                if(arr[flag]>arr[j])
                {
                    flag=j;
                }
            }
            if(flag!=i)//flag为这一轮最小的值,放到这一轮的第一个
            {
                int temp;
                temp=arr[i];
                arr[i]=arr[flag];
                arr[flag]=temp;
            }
        }
        System.out.println("排序后的数组顺序:");
        showArray(arr);
    }

    public static void showArray(int[] array) {
        for (int i : array) {
            System.out.print(i + "  ");
        }
    }
View Code

原文地址:https://www.cnblogs.com/weibanggang/p/10129436.html