<<AtA>>上的一道思考题.昨天开始琢磨,今天又琢磨到现在.我承认我脑袋比较迷糊,但也有点慢得让我接受不了了."不急跬步,无以至千里;不积小流,无以成江海",只能如此安慰自己了.呵呵.
问题本身就是,给定 N 个数的集合S, S {X | X ∈ S, 0 <= X <= k).恩.书上是1,我这里出现的是0.多了个数罢了.要求是,修改计数排序,以完成在 O (N + K) 时间完成排序的任务,并且只能使用 O (K) 的存储空间.
昨天刚看到的时候,比较迷糊.后来,搜了一下,便发现了方法.我想说的是,一旦我想照着别人去做,我往往做不好.并非就是如此给自己定义了,而确实是这回事呢.呵呵.自己知道方法后,安心地去写,其实还是可以的.老想着现成的东西是怎么做的,很难做好.还好,最终写出来了.不然心就堵死了,一晚上得憋气死...
核心的思想就是,把元素放在正确的位置上,放置完一种值,就将该值的计数 -1 , 当该值计数为 0 时,也就是,所有的此种值都已在正确的位置上,再次遇到无需处理,直接越过.直到,处理完所有数据.
我说得比较乱,呵呵.代码要来了,看代码吧.
typedef int Item ;
#define SIZE (30)
#define K (50)
int main (void) ;
void initializeArray (Item * const array, const int size, const Item k) ;
void countingSort (Item * const array, const int size, const Item k) ;
void swap (Item * const pFV, Item * const pSV) ;
void printArray (const Item * const array, const int size) ;
int main (void)
{
Item array[SIZE] ;
Item k = K ;
int size = SIZE ;
initializeArray (array, size, k) ;
printArray (array, size) ;
countingSort (array, size, k) ;
printArray (array, size) ;
return 0 ;
}
void initializeArray (Item * const array, const int size, const Item k)
{
int i ;
srand ((unsigned int) time (NULL)) ;
for (i = 0; i < size; i++)
array[i] = rand () % k + 1 ;
}
void countingSort (Item * const array, const int size, const Item k)
{
Item * count, * position ;
int i, index ;
count = (Item *) malloc (sizeof (Item) * (k + 1)) ;
if (NULL == count)
return ;
position = (Item *) malloc (sizeof (Item) * (k + 1)) ;
if (NULL == position)
{
free (count) ;
return ;
}
for (i = 0; i <= k; i++)
count[i] = 0 ;
for (i = 0; i < size; i++)
count[array[i]]++ ;
position[0] = count[0] ;
for (i = 1; i <= k; i++)
position[i] = position[i - 1] + count[i] ;
index = 0 ;
while (index < size)
{
while (index < size && 0 == count[array[index]])
index++ ;
if (size == index)
break ;
count[array[index]]-- ;
if (array[index] != array[--position[array[index]]])
swap (array + index, array + position[array[index]]) ;
}
free (count) ;
free (position) ;
}
void swap (Item * const pFV, Item * const pSV)
{
Item temp ;
temp = *pFV ;
*pFV = *pSV ;
*pSV = temp ;
}
void printArray (const Item * const array, const int size)
{
int i ;
for (i = 0; i < size; i++)
printf ("%d/n", array[i]) ;
putchar ('/n') ;
}