3 ms·
I guess it's a common question because it's usually taught in college because it's probably the simplest after select sort. Personally I've never found this ca
by brozaman 7y ago
I guess it's a common question because it's usually taught in college because it's probably the simplest after select sort.
Personally I've never found this case myself, but regarding why it's used some times, the O(n²) is the worst case scenario. The best case scenario is O(2n) which is really good, so for lists that are sorted or almost sorted it works well.
Other algorithms like timsort have O(n) for the best case scenario, but O(n) only tells you how many times you go through the loop.
Without actually measuring it, I would expect each iteration of timsort to be at more than twice as expensive as bubble sort, so in this case O(2n) would be cheaper than O(n).
When you know with a certain degree of certainty how is the data you expect in most cases, some times it's kinda easy to make a more efficient algorithm than the one that is the best for the average scenario.