计数排序(Counting-Sort)

来源:互联网 发布:腾讯企业邮箱域名 编辑:程序博客网 时间:2024/06/05 09:06

计数排序(Counting-Sort)

计数排序假设n个输入元素的每一个都是在0到k闭区间的一个整数,它的时间复杂度为O(n),下面是计数排序的Java实现:

import java.util.Arrays;/** * Created by CvShrimp on 2017/11/11. */public class CountingSort {    public static int[] countingSort(int[] array, int k) {        //k表示待排序数组的最大的元素值        int[] c = new int[k + 1];        for(int j = 0; j < array.length; j++) {            //c[i]记录原数组中等于i的元素的个数            c[array[j]] = c[array[j]] + 1;        }        for(int i = 1; i <= k; i++) {            //c[i]记录原数组中小于等于i的元素个数            c[i] = c[i] + c[i - 1];        }        int[] b = new int[array.length];        for(int j = array.length - 1; j >= 0; j--) {            b[c[array[j]] - 1] = array[j];            c[array[j]] = c[array[j]] - 1;        }        return b;    }    public static void main(String[] args) {        int[] array = {6,5,6,66,1,10,33};        int[] sortedArray = CountingSort.countingSort(array, 66);        System.out.println(Arrays.toString(sortedArray));    }}

执行结果如下所示:

[1, 5, 6, 6, 10, 33, 66]Process finished with exit code 0
原创粉丝点击