From c780f4303a34a120fbbc33a95ead17718794bef4 Mon Sep 17 00:00:00 2001 From: rylim <36293596+rylim@users.noreply.github.com> Date: Mon, 11 Oct 2021 18:03:25 -0700 Subject: [PATCH] Create 033-insertion-sort-python.md --- python/033-insertion-sort-python.md | 56 +++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 python/033-insertion-sort-python.md diff --git a/python/033-insertion-sort-python.md b/python/033-insertion-sort-python.md new file mode 100644 index 0000000..8281d3f --- /dev/null +++ b/python/033-insertion-sort-python.md @@ -0,0 +1,56 @@ +--- +id: 033-insertion-sort-python.md +title: Insertion Sort in Python +tags: + - python + - insertion sort + - sorting + - algorithms +date: 2021-10-11 17:30:00 -0800 +keywords: python, sorting, algorithms, insertion, sort +categories: + - python +cover: ../../images/categories/python.png +author: Ryan Lim +meta-description: insertion sort in python +--- + +# Insertion Sort in Python + +[Insertion Sort](https://en.wikipedia.org/wiki/Insertion_sort) is type of [sorting algorithm](https://en.wikipedia.org/wiki/Sorting_algorithm) that is relatively simple to implement. It does not have the best runtime, i.e. `O(n^2)`, compared to more advanced sorting algorithms such as [quicksort](https://en.wikipedia.org/wiki/Quicksort) or [merge sort](https://en.wikipedia.org/wiki/Merge_sort) but is a good starting sorting algorithm to learn. It can be used to sort smaller arrays consisting of strings or numbers. + +## Pseudocode + +Here is the pseudocode of insertion code (from [wikipedia](https://en.wikipedia.org/wiki/Insertion_sort#Algorithm)): + +``` +i ← 1 +while i < length(A) + j ← i + while j > 0 and A[j-1] > A[j] + swap A[j] and A[j-1] + j ← j - 1 + end while + i ← i + 1 +end while +``` + +The general idea behind it is to iterate through the array from beginning to end and swaps each element from the current element to the beginning of the array if a "greater" prior element is found compare to the current element. + +## Python Implementation + +Without further ado, here is my Python (3) implementation of it: + +```python +def insertion_sort(array): + for i in range(1, len(array)): + j = i + while j > 0 and array[j - 1] > array[j]: + temp = array[j - 1] + array[j - 1] = array[j] + array[j] = temp + j -= 1 + return array +``` + +Thanks for reading, any comment or feedback is most welcome!