其他语言

本类阅读TOP10

·基于Solaris 开发环境的整体构思
·使用AutoMake轻松生成Makefile
·BCB数据库图像保存技术
·GNU中的Makefile
·射频芯片nRF401天线设计的分析
·iframe 的自适应高度
·BCB之Socket通信
·软件企业如何实施CMM
·入门系列--OpenGL最简单的入门
·WIN95中日志钩子(JournalRecord Hook)的使用

分类导航
VC语言Delphi
VB语言ASP
PerlJava
Script数据库
其他语言游戏开发
文件格式网站制作
软件工程.NET开发
8.2 Counting sort

作者:未知 来源:月光软件站 加入时间:2005-2-28 月光软件站

<< Introduction to algorithms >> ( Second Edition )


8.2 Counting sort

Counting sort assumes that each of the n input elements is an integer in the range
0 to k, for some integer k. When k = O( n ), the sort runs in O( n ) time.
    The basic idea of counting sort is to determine, for each input element x, the
number of elements less than x. This information can be used to place element x
directly into its position in the output array. For example, if there are 17 elements
less than x, then x belongs in output position 18. This scheme must be modified
slightly to handle the situation in which several elements have the same value, since
we don't want to put them all in the same position.


Solution:

// 声明:本代码旨在实现原文的思想
// copyleft 2004    http://blog.csdn.net/mskia
// email:    [email protected]

#ifndef Counting_Sort_by_mskia
#define Counting_Sort_by_mskia

namespace te {
    void counting_sort( unsigned int *first , unsigned int *last ) {
        unsigned int max = 0;
        for ( unsigned  int *p = first; p <= last; ++p ) {
            if ( *p > max ) {
                max = *p;
            }
        }

        unsigned int len = max + 1;
        unsigned int *counter = new unsigned int [ len ];
        for ( unsigned int i = 0; i < len; ++i ) {
            counter[ i ] = 0;
        }

        for ( unsigned int *p = first; p <= last; ++p ) {
            ++counter[ *p ];
        }

        for ( unsigned int i = 0; i < len; ++i ) {
            unsigned int &t = counter[ i ];
            while ( t > 0 ) {
                *( first++ ) = i;
                --t;
            }
        }

        delete[] counter;

        return;
    }
}

#endif




相关文章

相关软件