forked from flashreads/blogs
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
56 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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! |