南大高级算法作业之计数排序

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 --;
    		
    //	}
    	
    
		}
	}
       
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值