Write a program to read a multiple line text file and write the ‘N’ longest lines to stdout.
There was a similar question but I didn’t really understand it since it involves using a min-heap and that would create more work since I’d have to create a min-heap data structure.
I tried to create an array that size n. Then sort it but I would have to sort it each and every time I inserted a new line into the array. I’d like to know what’s the simple approach and what would be the optimal one.
Create an array of N strings.
Loop through the file.
If the number of items in the array is < N then just add it to the end.
In all cases store the shortest length of the line in the array.
If the array is full, then compare to the shortest line, if the new line is > then that line, replace, and find the shortest line.
Repeat loop.
Print strings.