Sorting algorithms/Insertion sort: Difference between revisions

Content added Content deleted
(→‎{{header|Python}}: add Insertion sort with binary search)
Line 87: Line 87:
j -= 1
j -= 1
l[j+1] = key
l[j+1] = key

===Insertion sort with binary search===
<code>
def insertion_sort_bin(seq):
for i in range(1, len(seq)):
# invariant: ``seq[:i]`` is sorted
key = seq[i]
##
# find the least `low' such that ``seq[low]`` is not less then `key'.
# Binary search in sorted sequence ``seq[low:up]``:
low, up = 0, i
while up > low:
middle = (low + up) // 2
if seq[middle] < key:
low = middle + 1
else:
up = middle
##
# insert key at position ``low``
seq[:] = seq[:low] + [key] + seq[low:i] + seq[i + 1:]
return seq
</code>