Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About bubble sort vs merge sort

This is an interview question that I recently found on Internet:

If you are going to implement a function which takes an integer array as input and returns the maximum, would you use bubble sort or merge sort to implement this function? What if the array size is less than 1000? What if it is greater than 1000?

This is how I think about it:

First, it is really weird to use sorting to implement the above function. You can just go through the array once and find the max one. Second, if have to make a choice between the two, then bubble sort is better - you don't have to implement the whole bubble sort procedure but only need to do the first pass. It is better than merge sort both in time and space.

Are there any mistakes in my answer? Did I miss anything?

like image 367
quantumrose Avatar asked Mar 08 '13 03:03

quantumrose


2 Answers

It's a trick question. If you just want the maximum, (or indeed, the kth value for any k, which includes finding the median), there's a perfectly good O(n) algorithm. Sorting is a waste of time. That's what they want to hear.

As you say, the algorithm for maximum is really trivial. To ace a question like this, you should have the quick-select algorithm ready, and also be able to suggest a heap datastructure in case you need to be able to mutate the list of values and always be able to produce the maximum rapidly.

like image 104
rici Avatar answered Oct 24 '22 10:10

rici


I just googled the algorithms. The bubble sort wins in both situations because of the largest benefit of only having to run through it once. Merge sort can not cut any short cuts for only having to calculate the largest number. Merge takes the length of the list, finds the middle, and then all the numbers below the middle compare to the left and all above compare to the right; in oppose to creating unique pairs to compare. Meaning for every number left in the array an equal number of comparisons need to be made. In addition to that each number is compared twice so the lowest numbers of the array will most likely get eliminated in both of their comparisons. Meaning only one less number in the array after doing two comparisons in many situations. Bubble would dominate

like image 38
Four_lo Avatar answered Oct 24 '22 08:10

Four_lo