Task: Find 10 maximum numbers from a file that contains billions of numbers
Input:
97911
98855
12345
78982
.....
.....
I really came up with a solution below that has
- best degree of difficulty
O(n)- When a file has numbers in descending order - worst difficulty
O(n*10) ~ O(n)When a file is numbered in ascending order - Medium difficulty ~
O(n)
The complexity of space O(1)in all cases
I am reading a file using a file reader and a sorted array that stores a maximum of 10 numbers. I will check if the currentLine is larger than the smallest element in the array. If it will be inserted in the correct position by replacement.
Scanner sc = new Scanner(new FileReader(new File("demo.txt")));
int[] maxNum = new int[10];
while(sc.hasNext()){
int phoneNumber = Integer.parseInt(sc.nextLine());
if(phoneNumber>maxNum[9]){
maxNum[9] = phoneNumber;
for(int i =9;i>0;i--){
if(maxNum[i]>maxNum[i-1]){
int temp = maxNum[i];
maxNum[i] = maxNum[i-1];
maxNum[i-1] = temp;
}
}
}
}
,