If we need to implement a function that t开发者_JS百科akes 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? I am a bit confused on why I should use a particular algorithm over another one. Is it just due to its complexity and time or other factors also involved in this? What if I have to test out the above function and that takes a lot more time for a simple algorithm and less time for a complex one?
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)).
This site rocks
http://www.sorting-algorithms.com/
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.
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.
精彩评论