I'm writing a small algorithm in PHP that goes through n number of movies with ratings, and will store the top 5. I'm not reading from a datafile, but from a stream so I cannot simply order the movies by rating.
My question is what is the most efficent way to keep track of the top 5 rated movies as I read the stream? Currently I do the following:
- Read in 5 movies (into an array called movies[]), with two keys movies[][name] and movies[][rating]
- Order the array by movies[rating] using array_multisort() (highest rating now sits at movies[4])
- Read in the next movie
- If this new movie rating > movies[0][rating] then replace movies[0] with this new movie
- Re-order the list
- Repeat 3-5 until finished
My method works, but requires a sort on the list after every read. I believe this to be an expensive method mostly due to the fact that every time I use array_multisort() I must do a for loop on 5 movies just to build the index to sort on. Can anyone suggest a better way to approach this?