Sorting algorithms/Insertion sort: Difference between revisions
Content added Content deleted
(→Insertion sort with binary search: fix formatting) |
(→Insertion sort with binary search: fix formatting) |
||
Line 89: | Line 89: | ||
===Insertion sort with binary search=== |
===Insertion sort with binary search=== |
||
⚫ | |||
⚫ | |||
<code> |
|||
⚫ | |||
⚫ | |||
# invariant: ``seq[:i]`` is sorted |
|||
⚫ | |||
# |
# 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: |
|||
# find the least `low' such that ``seq[low]`` is not less then `key'. |
|||
middle = (low + up) // 2 |
|||
# Binary search in sorted sequence ``seq[low:up]``: |
|||
if seq[middle] < key: |
|||
low = middle + 1 |
|||
else: |
|||
up = middle |
|||
low |
# insert key at position ``low`` |
||
⚫ | |||
else: |
|||
⚫ | |||
⚫ | |||
## |
|||
# insert key at position ``low`` |
|||
⚫ | |||
⚫ | |||
</code> |