question about counting sort
hi i have write following code which prints elements in sorted order only one big problem is that it use two additional array here is my code
public class occurance{
public static final int n=5;
public static void main(String[]args){
// n is maximum possible value what it should be in array suppose n=5 then array may be
int a[]=new int[]{3,4,4,2,1,3,5};// as u see all elements are less or equal to n
//create array a.length*n
int b[]=new int[a.length*n];
int c[]=new int[b.length];
for (int i=0;i<b.length;i++){
b[i]=0;
c[i]=0;
}
for (int i=0;i<a.length;i++){
if (b[a[i]]==1){
c[开发者_如何学运维a[i]]=1;
}
else{
b[a[i]]=1;
}
}
for (int i=0;i<b.length;i++){
if (b[i]==1) {
System.out.println(i);
}
if (c[i]==1){
System.out.println(i);
}
}
}
}
//
1
2
3
3
4
4
5
1.i have two question what is complexity of this algorithm?i mean running time
2. how put this elements into other array with sorted order? thanks
The algorithm - as stated above - runs in O(n), where n is the size of array a
.
However, I even doubt that it works correctly.
So, here's a pseudocode-implementation of counting sort. It takes an array a
of integers and stores the sorted values in an integer array b
. a
and b
must be of equal length.
void countingSort(int[] a, int[] b){
// first of all: count occurences
int[] occ = new int[a.length];
for (int i = 0; i<a.length; ++i){
occ[i]=0;
}
for (int i = 0; i<a.length; ++i){
occ[a[i]] = occ[a[i]] + 1;
}
// second: put the elements in order into b
int s = 0;
for (int i = 0; i<a.length; ++i){
// how often did element i occur?
for (int j = 0; j<occ[i]; ++j){
b[s] = i;
s = s + 1;
}
}
}
I hope I did nothing terribly wrong.
精彩评论