input:
13 24 3 56 34 3 78 12 29 49 84 51 9 100
13 24 3 52 34 3 78 12 29 49 84 51 9 97
output:
3 3 9 12 24 29 34 49 51 56 78 84 100
3 3 9 12 24 29 34 49 51 52 78 84 97
计数排序就是统计比当前数组中某个数小的数字个数,通过这个个数来判断大小并进行排列,可以直接用map来保存当前数在数组中的pos,value保存比当前数小的个数,然后每次取出最小的value并输出,我闲着没事写了个新类...
代码:
import java.util.*;
class Information{
private int pos;
private int count;
Information(int pos,int count){
this.pos=pos;
this.count=count;
}
public int getPos(){
return pos;
}
public int getCount(){
return count;
}
public void setPos(int pos){
this.pos = pos;
}
public void setCount(int count){
this.count = count;
}
}
public class Main
{
//一次统计比该位置元素小的元素数量
public static int smallerCount(int[]element,int pos){
int count = 0;
for(int i=0;i < element.length;i ++){
if(element[i] < element[pos]){
count ++;
}
}
return count;
}
public static void main (String[] args){
Scanner scan = new Scanner(System.in);
while(scan.hasNext()){
// int e_num = Integer.parseInt(scan.nextLine());
// while(e_num > 0){
int num = scan.nextInt();//元素数
int[] element = new int[num];
for(int i=0;i < num;i ++){
element[i] = scan.nextInt();
}
Information[] info = new Information[num];//存放次数的数组
for(int i = 0;i < num;i ++){
info[i] = new Information(0,0);
}
for(int i = 0;i < num;i ++){
info[i].setPos(i);//将该点在原数组的位置存进去
info[i].setCount(smallerCount(element,i));//将比该点小的count存进去
}
for(int i=0;i < num;i ++){
int temp = i;
Information temp_info = info[i];
for(int j=i+1;j < num;j ++){
if(info[j].getCount() < info[temp].getCount()){
temp = j;
temp_info = info[j];
}
}
info[temp] = info[i];
info[i] = temp_info;
if(i == num-1){
System.out.print(element[info[i].getPos()]);
}else{
System.out.print(element[info[i].getPos()]+" ");
}
}
System.out.println();
// e_num --;
// }
}
}
}