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
Basically, the time needed for an insertion sort is composed of three factors.
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)
.