1
0
mirror of https://gitlab.com/magicalsoup/Highschool.git synced 2025-01-24 00:21:45 -05:00
highschool/Grade 10/Computer Science/ICS4U1/Sorting Methods/Insertion Sort.md

32 lines
1.2 KiB
Markdown
Raw Normal View History

2019-11-06 11:41:26 -05:00
# Inssertion sort
## What is Insertion sort
- a sorting algorithm
- dividng an array into sroted and unsorted sections
- removes elements in idividually from un unosrted section of the list and inserts it into its correct position in a new sorted seqeuence
## Algorithm
- Set a key for the sections after the 1st element
- repeat the following
- select first unsorted element as the key
- move sorted elements to the right to create space
- shift unsorted elemnet into correct position
- advance the key to the right by 1 element
- Tests first unsorted element (key) to last element of sorted section
- If key is larger, insertion sort leaves the element in place and hte next index's element becomes the key
- Else it finds the correct position within the sorted list
- Duplicate the larger element in to one ahead of its current index each time the key is tested
- By looping this, it makes space and inserts the key into that correct position
## Pseudo0code
```
for x = 1 : n
key = list[x]
y = x-1
while y >= 0 && key < list[y]
insert list[x] into the sorted sequence list[1 .. x-1]
list[y+1] = list[y]
y--
list[y+1] = key
```