Java中的基础排序算法(四):归并排序、基数排序

参考文章:https://mp.weixin.qq.com/s/VjqZNPg6dAEReAzqZcb_yw

原文链接:www.jianshu.com/p/5e171281a387

7.归并排序 —— 速度仅次于快排,内存少的时候使用,可以进行并行计算的时候使用。

  1. 选择相邻两个数组成一个有序序列。

  2. 选择相邻的两个有序序列组成一个有序序列。

  3. 重复第二步,直到全部组成一个有序序列。

public static void mergeSort(int[] numbers, int left, int right) {
    int t = 1;// 每组元素个数
    int size = right - left + 1;
    while (t < size) {
        int s = t;// 本次循环每组元素个数
        t = 2 * s;
        int i = left;
        while (i + (t - 1) < size) {
            merge(numbers, i, i + (s - 1), i + (t - 1));
            i += t;
        }
        if (i + (s - 1) < right)
            merge(numbers, i, i + (s - 1), right);
    }
}
private static void merge(int[] data, int p, int q, int r) {
    int[] B = new int[data.length];
    int s = p;
    int t = q + 1;
    int k = p;
    while (s <= q && t <= r) {
        if (data[s] <= data[t]) {
            B[k] = data[s];
            s++;
        } else {
            B[k] = data[t];
            t++;
        }
        k++;
    }
    if (s == q + 1)
        B[k++] = data[t++];
    else  
        B[k++] = data[s++];
    for (int i = p; i <= r; i++)
        data[i] = B[i];
}

8.基数排序 —— 用于大量数,很长的数进行排序时。

  1. 将所有的数的个位数取出,按照个位数进行排序,构成一个序列。

  2. 将新构成的所有的数的十位数取出,按照十位数进行排序,构成一个序列。

public void sort(int[] array) {
        //首先确定排序的趟数;
        int max = array[0];
        for (int i = 1; i < array.length; i++) {
            if (array[i] > max) {
                max = array[i];
            }
        }
        int time = 0;
        //判断位数;
        while (max > 0) {
            max /= 10;
            time++;
        }
        //建立10个队列;
        List<ArrayList> queue = new ArrayList<ArrayList>();
        for (int i = 0; i < 10; i++) {
            ArrayList<Integer> queue1 = new ArrayList<Integer>();
            queue.add(queue1);
        }
        //进行time次分配和收集;
        for (int i = 0; i < time; i++) {
            //分配数组元素;
            for (int j = 0; j < array.length; j++) {
                //得到数字的第time+1位数;
                int x = array[j] % (int) Math.pow(10, i + 1) / (int) Math.pow(10, i);
                ArrayList<Integer> queue2 = queue.get(x);
                queue2.add(array[j]);
                queue.set(x, queue2);
            }
            int count = 0;//元素计数器;
            //收集队列元素;
            for (int k = 0; k < 10; k++) {
                while (queue.get(k).size() > 0) {
                    ArrayList<Integer> queue3 = queue.get(k);
                    array[count] = queue3.get(0);
                    queue3.remove(0);
                    count++;
                }
            }
        }
    }
原文地址:https://www.cnblogs.com/lotuses/p/11640691.html