The Program of Algorithms ------- Sorting in Linear Time---- Counting Sort

Input: A[1...n], each 0<A[i]<=k

Output: B[1...n] = sorting of A

Auxiliary: C[1...k]


Restricts: 

1. each element little than a const "k"

2. the element should be integer

3. the range of the elements shoud not be so large (or it will cost more than nlgn and waste more space)


The idea about this algorithm:

About the arrary C, C[i] store the information about how many numbers in the array A which less than or equal "i".


To finish this task:

Step1: traverse the array A and C[A[i]]++. Such as A[0]=10, then the C[10]++.

Step2: use prefix sum to change the value in array C. After the transform C[i] give number of keys less than or equal i.

#include <iostream>
using namespace std;

int * CountSort(int* A,int p,int q,int bound){
	int size=q-p+1;
	int * C=new int[bound+1];
	int * B=new int[size];
	for(int i=0;i<=bound;i++){
		C[i]=0;
	}
	for(int i=0;i<size;i++){
		C[A[p+i]]++;
	}
	for(int i=1;i<=bound;i++){
		C[i]+=C[i-1];
	}
	for(int j=size-1;j>=0;j--){
		B[C[A[p+j]]-1]=A[p+j];
		C[A[p+j]]--;
	}
	return B;
}

int main(){

	int Arr[15]={1,4,3,6,2,6,3,5,4,9,2,4,6,7,3};
	int *Res;
	Res=CountSort(Arr,0,14,9);
	for(int i=0;i<14;i++){
		cout<<Res[i]<<" ";
	}
	return 0;
}

Advantage of Counting Sort: The Time Complexity is O(k+n), if k=O(n) the Time will be O(n), which beat all comparsion sort algorithm.

Disadvantage: It cost so many space. It can be represented as O(k).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值