In: Computer Science
assume n = 2^100. consider the following problem. given an unsorted list of size n you can choose to sort it or not first. after this step, you get m queries q1, q2, ... qm. one by one of the form "is qi in the list?" Describe whether you would sort and what algorithm you would use if 1.) m= 10, and 2) m = 1000
1) Consider the case when the list is not sorted. Then each
query will take n comparisons time to answer. Hence the time taken
will be proportional to
.
If the list is sorted, then sorting alone will take time at least
which is already more than the time taken to answer the queries
without sorting.
Hence it is better not to sort the list for answering the queries.
2) Now, when the list is not sorted, the time taken will be proportional to .
If the list is sorted, say using Merge sort, then it will take time proportional to . After this, each query will take comparisons to answer, hence the total time taken by the queries is proportional to . The total time taken in this process is . This is clearly less than when the list was not sorted.
Therefore the list should be sorted, using mergesort.
Comment in case of any doubts.