求排序一堆整数,数据都是有限范围的和有限个数的,对他们进行排序,要求O(n)的时间复杂度.

求排序一堆整数,数据都是有限范围的和有限个数的,任意数据都小于100000,个数也肯定小于100000,对他们进行排序,要求O(n)的时间复杂度.
思路:
(1)比如有一组数据arr={1,200,44,232,12,33,200},然后定义一个数组int[] count = new int[100000],初始化每一个数据值为0;
(2)然后扫描这个数组,然后count[arr[1]]++,即:
遇到1,则count[1]++;
遇到200,则count[200]++;
遇到44,则count[44]++;
遇到232,则count[232]++;
遇到12,则count[12]++;
遇到33,则count[33]++;
遇到200,则count[200]++;
(3)然后遍历这个count数组,如果count[i]>0的时候,表示数组中有多个相同的数,则输出多次i.

 

代码实现(Java):

public class CoolSort {
    public static void main(String[] args) {
        int[] count = new int[100000];
        int[] arr = { 1, 200, 44, 232, 9999, 9999, 12, 33, 200 };
        for (int i = 0; i < arr.length; i++) {

            count[arr[i]]++;
        }
        for (int i = 0; i < count.length; i++) {
            if (count[i] > 0) {
                for (int j = 0; j < count[i]; j++) {

                    System.out.println(i);
                }

            }

        }
    }
}

posted @ 2009-11-06 16:26  Chris Wang  阅读(549)  评论(0编辑  收藏  举报