Search code examples
algorithmmergesortbubble-sort

Algorithm for max integer in an array of integers


If we need 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? 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?


Solution

  • 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)).