Counting sort

Counting sort assumes that each of the n input elements is an integer in the range 0 to k.

 

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.

So, I give you an example.

We assume that the input is an array A[0...n-1], we require two other arrays: the array B[0...n-1] holdsthe sorted

output, and the array C[0...k] provides temporary working storage.

#include <stdio.h>
#include <malloc.h>

// n is the length of A, k is the max element
void counting_sort(int A[], int B[], int k, int n) 
{
	int *C, i;
	C = (int *)malloc(sizeof(int)*(k+1));
	for (i=0; i<k+1; i++)
	{
		C[i] = 0;
	}
	// C[i]contains the number of elements equal to i
	for (i=0; i<n; i++)
	{
		C[A[i]]++;
	}
	// C[i] now contains the number of elements less than or equal to i
	for (i=1; i<n; i++)
	{
		C[i] = C[i] + C[i-1];
	}
	
	//put the element A[i] to the right position
	for (i=n-1; i>=0; i--)
	{	
		B[C[A[i]]-1] = A[i];
	
		C[A[i]]--;
	}
	
	free(C);
	
	
}

int main()
{
	int k, n;
	int A[8] = {2, 5, 3, 0, 2, 3, 0, 3};
	int B[8];
	n = 8;
	k=5;
	counting_sort(A, B, k, n);
	for (k=0; k<n; k++)
	{
		printf("%d\t", B[k]);
	}
	printf("\n");
	
	
	return 0;
}

 And the output of B is

0    0    2    2    3    3    3    5

From "Introduction to algorithms"

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值