整数数组中最大整数的算法
如果我们需要实现一个函数,接受一个整数数组并返回集合中的最大整数,假设数组的长度小于1000。您会使用冒泡排序还是归并排序,为什么?
另外,如果数组长度大于 1000,上述算法选择会发生什么情况?我有点困惑为什么我应该使用一种特定的算法而不是另一种算法。仅仅是因为它的复杂性和时间还是还涉及其他因素?如果我必须测试上述函数,并且对于简单算法需要更多时间,而对于复杂算法需要更少时间,该怎么办?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我根本不会排序。我只需遍历数组并跟踪最大的一个。这需要 O(N) 时间,而排序算法通常不会比 O(N*log(N)) 更好。
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)).
该网站震撼
http://www.sorting-algorithms.com/
This site rocks
http://www.sorting-algorithms.com/
如果你必须排序,那么使用合并排序,因为它比冒泡排序快得多。对于 1000 个元素和单一排序,您可能不会注意到现代计算机上的差异,但对于更多元素(我认为 >= 10 000),差异变得明显。
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.
我们将数组的长度称为 N。
使用冒泡排序对数组进行排序大约需要 N*N 个时间单位。
使用归并排序对其进行排序需要 N * log N 单位时间。
简单地逐个查看每个元素并跟踪哪个元素最大将花费大约 N 个时间单位。
因此,使用最后一种方法。
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.