计数排序

本文介绍了一种简单的计数排序算法实现方式,并提供了一个具体的Java示例程序。该程序能够处理包含最大值为248的整数数组,通过创建计数数组来统计每个元素出现的次数并进行排序。
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 好吧,就是菜菜 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/shuiyonglewodezzzzz/p/7216320.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值