Best case time complexity for selection sort

假如想象 提交于 2019-12-23 22:27:15

问题


Why is the best case time complexity for selection sort O(n^2) when it is O(n) for insertion sort and bubble sort? Their average times are same. I don't understand why the best case times are different. Would appreciate some help.


回答1:


For selection sort you have to search the minimum and put it on the first place in the first iteration. In the second iteration you have to search the minimum in the non-sorted part of the array and put it to the second place and so on...

You only know which element is the minimum after iterate till the end of the non-sorted part. Even if the array is sorted(!) you have to iterate till the end. Then you know for sure you found the minimum to put it on the right place (at the end of the already sorted part)

So first iteration takes n steps to find the minimum. The second iteration takes n-1 steps to find the minimum in the non-sorted part ... The last iteration takes 1 step to find the minimum in the non-sorted part.

After these steps you have an sorted array (even it was sorted before). Selection sort does not check if the array is already sorted by an linear-time algorithm. Selection sort repeatedly searches the minimum. That's the way how selection sort works.

When you repeatedly search the minimum it takes n+(n-1)+...+1 so you get (n(n+1))/2 = (n²+n)/2 which is in O(n²)



来源:https://stackoverflow.com/questions/43298396/best-case-time-complexity-for-selection-sort

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!