比较笨的办法。效率有点低。 只是实现了功能。 期待牛人的算法。
我弄了个最佳方案 http://blog.csdn.net/yjflinchong/article/details/7533972 3秒就搞定了
一亿数字获取前100个最大的数字 这个方案需要700秒
///http://blog.csdn.net/yjflinchong/article/details/7532018
package com.my.util;
import java.io.*;
import java.util.*;
import java.net.*;
public class WebTest {
public static int last = 333333333;
public static int max = 100000000;//数据总数
public static int sp = 1000000;//分割数据条数
public static int[] ary = new int[100];
public static void main(String[] args) {
splitFile();
Date d1 = new Date();
find("d:/file/file.txt");
System.out.println(Arrays.toString(ary)+"========");
Date d2 = new Date();
System.out.println(d2.getTime()-d1.getTime());
}
public static void splitFile(){
StringBuffer str = new StringBuffer("");
int num = 1;
for (int i = 1; i < (max+1); i++) {
str.append(i+"\t\n");
if(i%1000000==0){
appendToFile("d:/file/file.txt", str.toString());
str = new StringBuffer("");
num++;
}
}
appendToFile("d:/file/file.txt", last+"");
}
public static void appendToFile(String file,String text){
try
{
FileWriter fw =new FileWriter(file,true);
BufferedWriter bw=new BufferedWriter(fw);
bw.write(text);
bw.flush();
}catch (Exception e) {
}
}
public static String readFile(String path){
StringBuffer str = new StringBuffer("");
try {
String line = null;
BufferedReader reader = new BufferedReader(new FileReader(path));
while ((line = reader.readLine()) != null) {
str.append(line);
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
return str.toString();
}
public static void find(int[] bak){
for (int i = 0; i < bak.length; i++) {
ary[0] = bak[i];
sort(ary);
}
}///http://blog.csdn.net/yjflinchong/article/details/7532018
public static void find(String path){
try {///http://blog.csdn.net/yjflinchong/
String line = null;
BufferedReader reader = new BufferedReader(new FileReader(path));
while ((line = reader.readLine()) != null) {
ary[0] = Integer.parseInt(line.trim());
sort(ary);
}
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
///http://blog.csdn.net/yjflinchong/article/details/7532018
public static void sort(int[] array){
for(int i = 0; i < array.length - 1; i++){
//当前值当作最小值
int min = array[i];
for(int j = i+1; j < array.length; j++){
if(min>array[j]){
//如果后面有比min值还小的就交换
min = array[j];
array[j] = array[i];
array[i] = min;
}
}
}
}
}