在一堆随机数中,找出最大的若干个

[代码] [Java]代码 import java.util.Random;

public class FindTop100_5 {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		final int N=100;
		int[] max = new int[N];
	 http://www.fpnanchang.com/linked/20130222.do; 	int index = 0;
		Random r = new Random();
		
		long start = System.currentTimeMillis();//计时开端
		while (index <100000000) {
			int temp = r.nextInt();
			 //System.out.print(temp   " ");
			// 前N个,选用疾速查找的方法找到最适宜方位,刺进新数据 并确保有序
			// 排序方法是从大到小 
			int low = 0;
			int high = Math.min(index, max.length - 1);
			int mid = 0;
			while (low <= high) {
				mid = (low   high) / 2;
				if (max[mid] < temp)
					high = mid - 1;
				else
					low = mid   1;
			}
			//判定新数的方位后移动数据,腾出空间放置新数
			//固然,可以新数在当时的数据下不能进入(比最小的还小),j>low就不会创建,数据不会移动
			for (int j = Math.min(index, max.length - 1); j > low; j--) {
				max[j] = max[j - 1];
			}
			if (low < max.length)//只需找到满意条件的个数的便可,避免越界
				max[low] = temp;// 放置到适宜方位
			  
			index  ;
		}
		long time = System.currentTimeMillis() - start;
		System.out.println("\n最大的"   max.length   "个是:");
		for (int t : max) {
			System.out.print(t   "\t");
		}
		
		System.out.println("\n耗时:"   time "毫秒");
	}

} http://www.fpfuzhou.com/linked/20130222.do;
相关文章
相关标签/搜索