Insertion Sort: Difference between revisions
mNo edit summary |
Add informal analysis. |
||
| Line 14: | Line 14: | ||
}}'''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: | }}'''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. | * '''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. | As the insertion sort operates, it is guaranteed that $[1, j-1]$ is sorted. | ||
== Informal Analysis == | |||
=== Loop Invariant === | |||
==== 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. | |||
Revision as of 14:29, 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
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.