Basic programming - Insertion Sort
Approach:
Need to use two for-loop. One is unsorted data in the range [i:n]
and the other is sorted data in the range [0:i]
.
Take one element from unsorted data to compare with sorted data.
Step 1: use temp
variable to store this element
Step 2: search value from sorted data which is bigger than temp
, if true, move the bigger value to current position vector[j] = vector[j - 1]
Step 3: Until if-statement returns false, it means the value of j - 1
is smaller than temp
, so insert temp
to current position vector[j] = temp
.
P.S. If input is sorted, just compare every elements once!
Space complexity: O(1)
Stable/Unstable: Stable
Source code
Version 1
1 |
|