Insertion sort vs Bubble Sort Algorithms

后端 未结 11 892
名媛妹妹
名媛妹妹 2020-12-07 08:51

I\'m trying to understand a few sorting algorithms, but I\'m struggling to see the difference in the bubble sort and insertion sort algorithm.

I know both are O(n

11条回答
  •  一整个雨季
    2020-12-07 09:45

    Though both the sorts are O(N^2).The hidden constants are much smaller in Insertion sort.Hidden constants refer to the actual number of primitive operations carried out.

    When insertion sort has better running time?

    1. Array is nearly sorted-notice that insertion sort does fewer operations in this case, than bubble sort.
    2. Array is of relatively small size: insertion sort you move elements around, to put the current element.This is only better than bubble sort if the number of elements is few.

    Notice that insertion sort is not always better than bubble sort.To get the best of both worlds, you can use insertion sort if array is of small size, and probably merge sort(or quicksort) for larger arrays.

提交回复
热议问题