Simple Sorting : Insertion Sort

The insertion sort is better than the bubble sort and the selection sort.

Process

For a better understanding, we will describe the process from the middle.
  1. Outer loop : Record the current value (e.g. index 6) as temp (The values at the left are partially sorted).
  2. Inner loop : Start comparison to the left
  3. For each Inner pass : [If inner - 1 > temp] then [move inner - 1 to inner] else [move temp to inner]
  4. Outer loop : move to the right (e.g. index 7)
  5. continue above steps until end of outer loop

Java:


Python:


The insertion sort runs in O(N2) time.

As a bonus, you can see below a version which removes duplicate:


Comments

Popular posts from this blog

Spring JPA : Using Specification with Projection

Chip input using Reactive Form