Insertion sort in 2 minutes

Michael Sambol · 1.9M views · 2016 · 2:19

Open on YouTube

Algorithms & data structuresEducation & learningexplainer

Why Stack Overflow recommends it

Stack Overflow users link it as a quick visual explanation when answering questions about how insertion sort works or comparing it with other simple sorts.

Recommended by 1 people across 1 different months, 2020 to 2024.

What it is

A short step-by-step animated walkthrough of how insertion sort works, presented by Michael Sambol. It shows the algorithm running on an example array, with an accompanying Python implementation linked in the description.

What people said

Recommends Zuhair Abid · 2024-07 · Stack Overflow · on “What can I do to understand this better?”

Let's break down this insertion sort algorithm step by step. Step-by-Step Guide to Insertion Sort: Initialization: We start with an unsorted array. In your example, data = [4, 1, 8, -3, 5, 7] . Iteration: For each element from the second position ( i = 1 ) to the end of the array: Store the current element in a temporary variable ( temp ). Initialize a pointer j to the current position ( i ). Comparisons and Shifting: While j > 0 and the element at position j-1 is greater than temp : Shift the element at position j-1 one position to the right (move it to position j ). Decrement j by 1. Insertion: Place the original temp value in the correct position ( array[j] ). Repeat: Repeat steps 2-4 for

Cites CLox · 2020-08 · Stack Overflow · on “Is there a better way to do Insertion Sort?”

YouTube Video to Insertion Sort - [this video] This is my implementation of it in C void insertionSort(void *data, uint32_t length, int8_t compareTo(const void * const, const void * const), const size_t bytes){ uint32_t i; for(i = 0; i < length; i++){ uint8_t isSorted; int32_t j; isSorted = 0; for(j = i - 1; j > -1 && !isSorted; j--){ isSorted = 1; if(compareTo((int8_t *)data + j * bytes, (int8_t *)data + (j + 1) * bytes) > 0){ uint32_t byteIndex; void *valCopy; valCopy = malloc(bytes); memcpy(valCopy, (int8_t *)data + j * bytes, bytes); for(byteIndex = 0; byteIndex < bytes; byteIndex++){ *((int8_t *)data + (j * bytes + byteIndex)) = *((int8_t *)data + ((j + 1) * bytes + byteIndex)); *((int8_t *)

Cites PankajShah · 2021-10 · Stack Overflow · on “Straight selection sort vs. exchange selection sort”

Both the algorithms have the same technique. However, the only difference between the two is that in the selection sort, only the index is updated every time the comparison is made and the swapping happens at the end of an iteration. On the other hand, in exchange sort, the swapping happens as soon as the element on the right side is smaller than the one which is present at the current position. For reference, you can see these 2-minute videos: Insertion sort: [this video] Exchange sort: [LINK]