Skip to content

insertion-sort-chapter #216

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 41 additions & 0 deletions chapters/sorting_searching/insertion_sort/c/insertion_sort.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#include <stdio.h>

void print_array(int *array, int arr_len){

putchar('[');
for(int i = 0; i < arr_len; i++){
if(i < (arr_len - 1))
printf("%d, ", array[i]);
else
printf("%d]\n", array[i]);
}
}

/*Insertion sort sorts the array inplace*/
void insertion_sort(int *array, int arr_len){

/*loop through array[1:n], array[0] is already sorted*/
for(int j = 1; j < arr_len; ++j){
int current_element = array[j];

/*Place the j-th element to the correct position in the sub array array[0...j]
Keeping array[0...j] sorted*/
int i = j - 1;
while((i >= 0) && (array[i] > current_element)){
array[i + 1] = array[i];
i -= 1;
}
array[i + 1] = current_element;
}
}

int main(){
int arr_len = 10;
int array[] = {10, 1, 3, 4, 7, 2, 5, 9, 6, 8};

printf("This is the array after sorting: ");
insertion_sort(array, arr_len);
print_array(array, arr_len);

return 0;
}
54 changes: 54 additions & 0 deletions chapters/sorting_searching/insertion_sort/insertion_sort.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# Insertion Sort
Insertion sort is the first algorithm usually taught in an introductory algorithms course since it is simple to understand as it is used regulary to sort decks of cards. Insertion sort has one important rule which is helpful to keep in mind, in the j-th iteration the subarray A[1...j-1] is sorted, it means that all the elements which the algorithm iterated over, are sorted.

The algorithm starts from the second element in the array, in this point the subarray A[1...j-1], which is A[1], is obviously sorted, since it holds only one element.

{% method %}
{% sample lang="c" %}
[import:18-19, lang:"c"](code/c/insertion_sort.c)
{% sample lang="py" %}
[import:5-6, lang:"python"](code/python/insertion_sort.py)
{% endmethod %}

In each iteration the current , j-th, element of A, A[j], is inserted into the correct position in the subarray A[1...j], moving each element that is bigger than A[j] one position to the right, leaving room for A[j].

{% method %}
{% sample lang="c" %}
[import:23-28, lang:"c"](code/c/insertion_sort.c)
{% sample lang="py" %}
[import:10-15, lang:"python"](code/python/insertion_sort.py)
{% endmethod %}


The worst input for insertion sort is the reverse sorted array, since in each iteration of the inner while loop will iterate over the entire A[1...j-1] array, moving each element one position to the right, this is why it has time complexity of $$\mathcal{O}(n^2)$$.

And the full code:
{% method %}
{% sample lang="c" %}
[import:14-41, lang:"c"](code/python/insertion_sort.c)
{% sample lang="py" %}
[import:1-24, lang:"python"](code/python/insertion_sort.py)
{% endmethod %}

<script>
MathJax.Hub.Queue(["Typeset",MathJax.Hub]);
</script>
$$
\newcommand{\d}{\mathrm{d}}
\newcommand{\bff}{\boldsymbol{f}}
\newcommand{\bfg}{\boldsymbol{g}}
\newcommand{\bfp}{\boldsymbol{p}}
\newcommand{\bfq}{\boldsymbol{q}}
\newcommand{\bfx}{\boldsymbol{x}}
\newcommand{\bfu}{\boldsymbol{u}}
\newcommand{\bfv}{\boldsymbol{v}}
\newcommand{\bfA}{\boldsymbol{A}}
\newcommand{\bfB}{\boldsymbol{B}}
\newcommand{\bfC}{\boldsymbol{C}}
\newcommand{\bfM}{\boldsymbol{M}}
\newcommand{\bfJ}{\boldsymbol{J}}
\newcommand{\bfR}{\boldsymbol{R}}
\newcommand{\bfT}{\boldsymbol{T}}
\newcommand{\bfomega}{\boldsymbol{\omega}}
\newcommand{\bftau}{\boldsymbol{\tau}}
$$
24 changes: 24 additions & 0 deletions chapters/sorting_searching/insertion_sort/python/insertion_sort.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
def insertion_sort(array):

array_length = len(array)
# loop through array[1:n], array[0] is already sorted
for j in range(1, array_length):
current_element = array[j]

# Place the j-th element to the correct position in the sub array array[0...j]
# Keeping array[0...j] sorted
i = j - 1
while((i >= 0) and (array[i] > current_element)):
array[i + 1] = array[i]
i -= 1

array[i + 1] = current_element

return array


if __name__ == '__main__':
array = [10, 1, 3, 4, 7, 2, 5, 9, 6, 8]
sorted_array = insertion_sort(array)

print("This is the array of sorting: " + str(sorted_array))