I'm working on a program that takes in a bunch (y) of integers and then needs to return the x highest integers in order. This code needs to be as fast as possible, but at the moment I dont think I have the best algorithm.
My approach/algorithm so far is to create a sorted list of integers (high to low) that have already been input and then handle each item as it comes in. For the first x items, I maintain a sorted array of integers, and when each new item comes in, I figure out where it should be placed using a binary sort. (Im also considering just taking in the first x items and then quick sorting them, but I dont know if this is faster) After the first x items have been sorted I then consider the rest of the items by first seeing if they qualify to enter the already sorted list of highest integers (by seeing if the new integer is greater than the integer at the end of the list) and if it does, add it to the sorted list via a binary search and remove the integer at the end of the list.
I was wondering if anyone had any advice as to how I can make this faster, or perhaps an entire new approach that is faster than this. Thanks.
x + 1slots for thexhighest integers and do binary insertion in that list. The time complexity will bey log(x)which checks out:1highest number meansycomplexity whiley - 1highest numbers means "alsmost" sorted input in which case you havey log(y):)10forx = 1000(log(1000)=10). I'm assuming thatxmay be of any value (for examplex = sqrt(y)). Or do I miss something here?xvalues in order, or just the highestxvalues? (Yes, it does make a difference.)