10000+個の数字の中でtop 100を探し出して、私の解法

1518 ワード


public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		
		// 10000+ 
		int[] input = new int[100000];
		Random r = new Random();
		for(int i=0;i<input.length;++i){
			input[i] = Math.abs(r.nextInt(10000));
		}
		
		int[] result = topN(input,100);
		
		for(int j=0;j<result.length;++j){
			System.out.print(result[j]+" ");
		}
		
	}
	
	public static int[] topN(int[] input,int top){
		int[] result = new int[top];
		
		if(input.length <= top){
			for(int i=0;i<input.length;++i){
				result[i] = input[i];
			}
			Arrays.sort(result);
			return result;
		}
		
		for(int j=0;j<top;++j){
			result[j] = input[j];
		}
		Arrays.sort(result);
		
		outer:for(int k=top;k<input.length;++k){
			if(input[k] <= result[0]){
				continue;
			}
			
			int pointer = -1;
			int bigger = input[k];
			
			for(int m=0;m<top;++m){
				if(bigger == result[m]){
					continue outer;
				}else if(bigger > result[m]){
					pointer = m;
				}
			}
			
			// 
			for(int n=0;n<pointer;++n){
				result[n] = result[n+1];
			}
			result[pointer] = bigger;
			
		}
		
		return result;
	}

}