三位数排序,数组排序

三位数简单排序

给三位数进行排序,三位数排序应该是很简单的,还是用了一天多的时间,总共掌握了两种方法,一种是简单的常规排序,就是每个数都比较一次,然后写出结果,以下是第一种方法:

public class Count {
    /**
     * 给出三位数,进行三位数排序
     * 
     * @param args
     */

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        int a = 100;
        int b = 93;
        int c = 56;
        if(a>=b) {
                int temp=a;
                a=b;
                b=temp;
            }
            if(a>=c) {
                int temp=a;
                a=c;
                c=temp;
            }
            if(b>=c) {
                int temp=b;
                b=c;
                c=temp;
            }

        System.out.println(a + "\n" + b + "\n" + c);
    }
}

此假设的逻辑是假设a是最大的,a和其他数一一比较,则设置a为临时变量temp,通过相等的方式,把temp赋值给比较的数字,其他数值依此论推;
若是要倒序,则把“>”改为“<”;

四位数排序

用这种方法也可以比较四位数的,只是,缺点是数字越多,比较起来越麻烦

public class Count1 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        // 给出一个四位数,进行排序
        /**
         * 注意:复制过程中,要改参数,不该参数,就会出问题,我就是没改参数费了好大的力气,以为方法有问题 
         * 
         */
        int a = 5;
        int b = 6;
        int c = 2;
        int d = 4;
        if (a >= b) {
            int temp = a;
            a = b;
            b = temp;
        }
        if (a >= c) {
            int temp = a;
            a = c;
            c = temp;
        }
        if (a >= d) {
            int temp = a;
            a = d;
            d = temp;
        }
        if (b >= c) {
            int temp = b;
            b = c;
            c = temp;
        }
        if (b >= d) {
            int temp = b;
            b = d;
            d = temp;
        }
        if (c >= d) {
            int temp = c;
            c = d;
            d = temp;
        }
        System.out.println(a + "\n" + b + "\n" + c + "\n" + d);
    }

}

数组排序、冒泡排序

相比于常规方法,数据排序/冒泡排序简单,理解却很有难度,以下是代码,感受下

public class Array {

/**
 * 给出一个数组,进行数组里面的值进行排序
 * 
 * @param args
 */

public static void main(String[] args) {

    int array[] = { 26, 12, 67, 45, 89, 32 };

    for (int i = 0; i <array.length; i++) {
        for (int j = 0; j <array.length - i - 1; j++) {
            if (array[j] >= array[j + 1]) {
                int temp = array[j + 1];
                array[j + 1] = array[j];
                array[j] = temp;

            }
        }

    }

    for (int x : array) {
        System.out.println(x);
    }
}

}

第一个for定义的是数的长度
第二个for定义的数组排序的位置,怎么理解这句话,从下面的if可以看出来:

if (array[j] >= array[j + 1]) {
                    int temp = array[j + 1];
                    array[j + 1] = array[j];
                    array[j] = temp;

假设一组数的长度[ 26, 12, 67, 45, 89, 32 ],那么,前面的数比后面的数大,则向后移,后面的往前移,我觉得这个表达式要表达的就是这么个结果,如果对于普通表达式有所理解,赋值变量这方面也就理解了

难点在于对“j

猜你喜欢

转载自blog.csdn.net/qq_42960881/article/details/82386001