Insertion Sort: Difference between revisions
Add informal analysis. |
No edit summary |
||
| Line 22: | Line 22: | ||
== Informal Analysis == | == Informal Analysis == | ||
=== Loop Invariant === | === Loop Invariant<ref>Cormen, Thomas H.; Leiserson, Charles E.; Rivest, Ronald L.; Stein, Clifford (2009). Introduction to Algorithms (3rd ed.). Cambridge, MA: The MIT Press. ISBN 978-0-262-03384-8.</ref> === | ||
==== Initialization ==== | ==== Initialization ==== | ||
| Line 29: | Line 29: | ||
==== Maintenance ==== | ==== Maintenance ==== | ||
During maintenance, each key points to the right side if the condition at Line $4$ is met, and by Line $7$ an empty space is left to be inserted. After Line $7$ is executed, subarray $[1 \cdot \cdot j]$ is sorted, and afterwards we increment $j$ for next iteration. | During maintenance, each key points to the right side if the condition at Line $4$ is met, and by Line $7$ an empty space is left to be inserted. After Line $7$ is executed, subarray $[1 \cdot \cdot j]$ is sorted, and afterwards we increment $j$ for next iteration. | ||
== References == | |||
<references /> | |||
Revision as of 14:31, 4 August 2026
This article is a stub. It might be missing pseudocode, complexity analysis, or a correctness sketch. It might need some other information which is incomplete perhaps.
- for i = 2 to A.length
- key = A[i]
- j = i - 1
- while j > 0 and A[j] > key
- A[j + 1] = A[j]
- j = j - 1
- A[j + 1] = key
Insertion sort is an algorithm for Sorting Problem, arranging an un-ordered list to an ordered list. We assume the first element of the un-ordered list to be ordered such that:
- Subarray: $[1, j-1]$ is sorted.
- Key: $[j]$ is the key we concern with.
- Subarray: $[j+1, A.length]$ is concerned.
As the insertion sort operates, it is guaranteed that $[1, j-1]$ is sorted.
Informal Analysis
Loop Invariant[1]
Initialization
It is true prior to the first iteration of loop. As we start with $j$ as $2$, we assumed it as trivial that $A[1]$ is sorted.
Maintenance
During maintenance, each key points to the right side if the condition at Line $4$ is met, and by Line $7$ an empty space is left to be inserted. After Line $7$ is executed, subarray $[1 \cdot \cdot j]$ is sorted, and afterwards we increment $j$ for next iteration.
References
- ↑ Cormen, Thomas H.; Leiserson, Charles E.; Rivest, Ronald L.; Stein, Clifford (2009). Introduction to Algorithms (3rd ed.). Cambridge, MA: The MIT Press. ISBN 978-0-262-03384-8.