Problem Statement: Find 10 maximum numbers from a file which contains billions of numbers
Input:
97911
98855
12345
78982
.....
.....
I actually came up with the below solution which has
- best case complexity
O(n)
- When file has numbers in descending order - worst case complexity
O(n*10) ~ O(n)
When the file has numbers in ascending order - Average
complexity ~
O(n)
Space complexity is O(1)
in all cases
I am reading the file using a file reader and an sorted Array which stores the maximum 10 numbers. I will check if the currentLine is greater than the smallest element in the array - If so will insert it in the correct position by swapping.
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;
}
}
}
}
I am looking for feedback if there are better ways to implement this