Improving worst-case running time of insertion sort using binary search

前端 未结 4 607
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-15 00:34

The while loop uses linear search to scan backwards. However, we know that the array within the while loop is already sorted. So we can replace the linear search with binary

4条回答
  •  悲哀的现实
    2021-01-15 01:09

    Basically, the time needed for an insertion sort is composed of three factors.

    1. Going over every element in the SOURCE array
    2. Finding the right location to insert it into the DESTINATION array
    3. Doing the insert.

    What you are talking about concerns step 2. A naive way would be to go through the full DESTINATION array to find the insert location, which takes O(n). However, you can do a binary search which would only take you O(log(n)).

    You still need to do the insert, but the cost of that is dependent on the data structure. If you use a linked list, it will always take you a constant amount of time. If you use a simple Array, you can just do a memcpy() which should scale equally well. The approach you use in pseudo-code is a very naive approach and would never be valid in a real implementation. See http://www.docjar.com/html/api/java/util/ArrayList.java.html#421 for a real-life example of an INSERT for Arrays. System.arraycopy() is O(1).

提交回复
热议问题