Search code examples
algorithmsortingsearchbinary-searchlinear-search

Binary search + Sorting vs. Linear search (Big O)


i have a question on a problem i am working on. I have to play Videos randomly in order without repeating a video. Each video is only allowed to be played once per playlist. Each video has an unique id from 0 up to max_video_count which is determined on runtime (depending on the server).

What i do now is, i created a linked list which adds the unique id of each video played. Than i create randomly a random number between 0 and max_video_count , do linear search if the number is already in the linked list and if yes i calculate a new number.. and again linear search .. and so on!!

obvisiouly this isn't very practical and sometimes it takes way to long to find an element. especially when a lot of videos were played already.

So i thought, i implement binear search instead of linear search but that brings me to the problem that i have to sort the list first. So, my next step was to think, that i sort the list while inserting the new unique_id and than do binary search.

I know that binary search is O(log n) compared to O(n) linear search which is a great advancement. But sorting the list is also O(n) because to find the right spot i would have to do linear search again..... So i come to the solution than that binary search would be O(log N * n) compared to O(n) linear search -> linear search fast. Is that right? Maybe my whole approach is wrong.. but i couldn't come up with something better yet...

I am quite new to algorithms so it would be nice if someone could enlighten me here :-)

Greetings Markus


Solution

  • You are essentially just looking at a random permutation. Arrange your videos in one fixed list, and then, to create the playlist, produce a random permutation of that list and play the permuted list.

    A typical and efficient (O(n)) way to achieve such a permutation is via a Knuth Shuffle.

    (Practically, you can of course just create a random permutation of an index set and play the items in order of the permuted indices.)