菜菜

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class CountingSort
{
    public static void main(String[] args) throws FileNotFoundException
    {
        //Scanner scanner = new Scanner(new FileInputStream("d:\\2.txt"));
//        int n;
//        while(scanner.hasNextInt())
//        {
//            n = scanner.nextInt();
//            int a[] = new int[n];
//            int max = -1;
//            for(int i = 0; i < n;i++)
//            {
//                a[i] = scanner.nextInt();
//                max = Math.max(max, a[i]);
//            }
//        }
        int a[] = {0,1,2,0,4,8,9,7,6,2,3,1,2,3,1,10,12,15,14,13,16,18,12,248,4,1,3};
        int max = 248;
        countingSort(a, max);
    }
    
    public static void countingSort(int a[],int k)
    {
        int c[] = new int[k+1];
        int b[] = new int[a.length];
        for(int i = 0; i < a.length;i++)
            c[a[i]]++;
        for(int i = 1; i < c.length;i++)
            c[i] = c[i-1]+c[i];
        for(int i = a.length-1; i >= 0;i--)
        {
            b[c[a[i]]-1] = a[i];
            c[a[i]]--;
        }
        for(int i = 0; i < b.length;i++)
            System.err.print(" "+b[i]);
        System.out.println();
    }
    

}

使用一个数组统计数据应该存放的位置

posted on 2017-07-21 10:19  好吧,就是菜菜  阅读(175)  评论(0编辑  收藏  举报