views:

121

answers:

4

Explain which algorithm you would use to implement a function that takes an array of integers and returns the maximum integer in the collection, assuming that the length of the array is less than 1000. Would you use Bubble Sort or Merge Sort and Why?

Also, what happens to the above algorithm choice, if the array length is greater than 1000?

+16  A: 

I wouldn't sort at all. I'd just traverse the array and keep track of the largest one as I go. This takes O(N) time, whereas a sort algorithms generally won't do better than O(N*log(N)).

Marcelo Cantos
+1: OP's intention to sort is bizarre for this. I wonder if there is another underlying requirement.
High Performance Mark
Also sorting can get worse than O(N * logN) if you choose a bad algorithm
Gishu
A: 

Lets call the length of your array N.

Sorting the array using Bubble Sort takes roughly in the order of N*N units of time.

Sorting it using Merge Sort takes in the order of N * log N units of time.

Simply looking at each element one after one and keeping track of which one is the biggest will take in the order of N units of time.

Hence, use the last method.

Jakob
+2  A: 

Well if you MUST sort, then use merge sort because it's a lot faster than bubble sort. For 1000 elements and a single sort you probably won't notice the difference on a modern computer, but for more elements (I'm thinking >= 10 000) the difference becomes notieceable.

IVlad
+3  A: 

This site rocks

http://www.sorting-algorithms.com/

Daniel Dolz
+1, not directly related to the question though :P but good site.
codaddict