算法----数组的排序(冒泡 选择 插入)

来源:互联网 发布:可牛软件下载 编辑:程序博客网 时间:2024/06/18 15:24
package forwhiledo;public class TestMaoPao {    public static void main(String[] args) {        TestMaoPao t = new TestMaoPao();        int a[] = new int[] { 4, 5, 6, 7, 8, 9, 10 };        t.sort3(a);        for (int i = 0; i < a.length; i++) {            System.out.print(a[i] + "\t");        }        System.out.println();    }    /**     * 插入排序     * 将数列分为有序和无序两个部分,每次处理就是将无序数列的第一个元素与有序数列的元素从后往前逐个进行比较,     * 找出插入位置,将该元素插入到有序数列的合适位置中。     */    public int[] sort3(int[] a) {        for (int i = 1; i < a.length; i++) {            for (int j = i; j > 0; j--) {                if (a[j] > a[j - 1]) {                    int amp = a[j];                    a[j] = a[j - 1];                    a[j - 1] = amp;                }            }        }        return a;    }    /**     * 选择排序     * 每一次从待排序的数据元素中取出最大,或者最小的一个元素,顺序放在已经排好序的最后,知道全部排序完成     * 从大到小排     */    public int[] sort2(int[] a) {        int max;        int indexmax;        for (int i = 0; i < a.length - 1; i++) {            max = a[i];            indexmax = i;            for (int j = i + 1; j < a.length; j++) {                if (max < a[j]) {                    max = a[j];                    indexmax = j;                }            }            if (a[i] != max && indexmax != i) {                a[indexmax] = a[i];                a[i] = max;            }        }        return a;    }    /**     * 冒泡排序     * 排序依据:一次比较相邻的两个元素,通过一次排序将未排序的元素中的最大或者最小值放在最后。     */    public int[] sort1(int[] a) {        for (int i = 0; i < a.length - 1; i++) {            for (int j = 0; j < a.length - 1 - i; j++) {                if (a[j] > a[j + 1]) {                    int temp = a[j];                    a[j] = a[j + 1];                    a[j + 1] = temp;                }            }        }        return a;    }}
0 0
原创粉丝点击