{"id":153,"date":"2026-07-15T15:13:49","date_gmt":"2026-07-15T15:13:49","guid":{"rendered":"https:\/\/blog.csfree.org\/?p=153"},"modified":"2026-07-15T15:13:49","modified_gmt":"2026-07-15T15:13:49","slug":"insertion-sort-explained-a-step-by-step-technical-guide","status":"publish","type":"post","link":"https:\/\/blog.csfree.org\/index.php\/2026\/07\/15\/insertion-sort-explained-a-step-by-step-technical-guide\/","title":{"rendered":"Insertion Sort Explained: A Step-by-Step Technical Guide"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\"><strong>Insertion Sort Explained: A Step-by-Step Technical Guide<\/strong><\/h2>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Insertion Sort<\/strong> is an elegant simplicity and practical, real-world utility.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What is an Insertion Sort?<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Imagine you\u2019re dealt a hand of playing cards. To sort them, you don&#8217;t spread them all over the table. Instead, you keep a sorted group on the left, pick up one unsorted card at a time, and slide it directly into its rightful spot, shifting the other cards over to make room.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">That is exactly how <strong>Insertion Sort<\/strong> works. It is a highly intuitive, comparison-based algorithm operating on the &#8220;incremental build&#8221; principle. Instead of trying to reorganize the entire array at once, it processes the list element-by-element, maintaining a sorted section on the left and sliding each new element from the unsorted right section into its proper place.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Because it performs these quick, local shifts entirely &#8220;in-place,&#8221; it requires absolutely zero extra memory workspace (O(1) auxiliary space), making it incredibly lightweight.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Why it\u2019s better than Selection or Bubble Sort:<\/strong> While <strong>Bubble Sort<\/strong> mindlessly swaps elements back and forth and <strong>Selection Sort stubbornly scans the entire remaining list every single time, Insertion Sort is brilliantly adaptive. If your data is already nearly sorted, it ba<\/strong>rely glances at it, running at a lightning-fast linear speed (O(n)). It is so efficient on a small scale that high-powered algorithms like <strong>Merge Sort<\/strong> actually hand off their final, small-scale sorting steps to <strong>Insertion Sort<\/strong> to finish the job.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What are its characteristics?<\/h3>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Super Stable Sorting<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Insertion Sort <\/strong>preserves the original order of duplicate values. When sliding a number into the sorted section, the algorithm stops shifting the moment it hits an equal value. Because identical numbers never leapfrog over each other, your data stays perfectly consistent.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Zero Extra Space (O(1) Space)<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">This is an &#8220;in-place&#8221; algorithm that sorts your data directly inside the original list. It requires virtually zero extra memory, using just a single temporary variable to hold one number while shifting others. This makes it incredibly lightweight and perfect for systems with strict memory limits.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Smart, Adaptive Speed<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">The algorithm&#8217;s speed dynamically adapts to how organized your data already is. If the list is already sorted, it glides through in a single quick pass at lightning-fast linear speed. However, if the list is completely backward, it is forced to shift every single number, dropping its performance to a slow quadratic pace.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Time and Space Complexity<\/strong><\/li>\n<\/ul>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Best Case: O(n)<\/strong> -> Already sorted data (one quick scan, zero shifting).<\/li>\n\n\n\n<li><strong>Worst\/Average Case: O(<\/strong><math data-latex=\"n^2\"><semantics><msup><mi>n<\/mi><mn>2<\/mn><\/msup><annotation encoding=\"application\/x-tex\">n^2<\/annotation><\/semantics><\/math><strong>)<\/strong> -> Reverse or randomized data (heavy, repetitive shifting).<\/li>\n\n\n\n<li><strong>Space Complexity: O(1)<\/strong> ->  Entirely in-place with no extra helper arrays needed.<\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\">(<strong>Note<\/strong>: While slow for massive datasets, Insertion Sort is extremely fast for <strong>small lists (under 15 items)<\/strong> and <strong>nearly sorted data<\/strong>. In fact, major programming languages like Python and Java use hybrid algorithms (like Timsort) that automatically switch to Insertion Sort to finish up the final, small-scale sorting.)<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Step-By-Step Example<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">Let&#8217;s see how <strong>Insertion Sort<\/strong> works on a array: <code>[8, 3, 1, 9, 5, 4]<\/code>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">We start with the first element (<code>8<\/code>) as our sorted section, and process the rest one by one.<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Step 1: Sort the 2nd element (Key = 3)<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Array<\/strong>: [8, 3, 1, 9, 5, 4].<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Compare <strong>3<\/strong> with <strong>8<\/strong>.<\/li>\n\n\n\n<li>Since 8 is greater than 3, we shift <strong>8<\/strong> to the right.<\/li>\n\n\n\n<li>Insert <strong>3<\/strong> into the vacant first spot.<\/li>\n\n\n\n<li><strong>Result:<\/strong> <code>[3, 8, 1, 9, 5, 4]<\/code><\/li>\n<\/ol>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Sort the 3rd element (Key = 1)<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Array<\/strong>: [3, 8, 1, 9, 5, 4].<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Compare <strong>1<\/strong> with <strong>8<\/strong> (shift 8) and then with <strong>3<\/strong> (shift 3).<\/li>\n\n\n\n<li>Since both are greater than 1, we shift both to the right.<\/li>\n\n\n\n<li>Insert <strong>1<\/strong> at the very beginning.<\/li>\n\n\n\n<li><strong>Result:<\/strong> <code>[1, 3, 8, 9, 5, 4]<\/code><\/li>\n<\/ol>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Sort the 4th element (Key = 9)<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Array<\/strong>: [1, 3, 8, 9, 5, 4].<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Compare <strong>9<\/strong> with the sorted neighbor <strong>8<\/strong>.<\/li>\n\n\n\n<li>Since 8 is less than 9, no shifting is needed.<\/li>\n\n\n\n<li><strong>9<\/strong> stays right where it is.<\/li>\n\n\n\n<li><strong>Result:<\/strong> <code>[1, 3, 8, 9, 5, 4]<\/code><\/li>\n<\/ol>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Sort the 5th element (Key = 5)<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Array<\/strong>: [1, 3, 8, 9, 5, 4].<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Compare <strong>5<\/strong> with <strong>9<\/strong> (shift 9) and <strong>8<\/strong> (shift 8).<\/li>\n\n\n\n<li>When we compare <strong>5<\/strong> with <strong>3<\/strong>, we stop because 3 is less than 5.<\/li>\n\n\n\n<li>Insert <strong>5<\/strong> into the gap right after 3.<\/li>\n\n\n\n<li><strong>Result:<\/strong> <code>[1, 3, 5, 8, 9, 4]<\/code><\/li>\n<\/ol>\n\n\n\n<ul class=\"wp-block-list\">\n<li><strong>Sort the 6th element (Key = 4)<\/strong><\/li>\n<\/ul>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>Array<\/strong>: [1, 3, 5, 8, 9, 4].<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Compare <strong>4<\/strong> with <strong>9<\/strong> (shift 9), <strong>8<\/strong> (shift 8), and <strong>5<\/strong> (shift 5).<\/li>\n\n\n\n<li>Stop comparing when we hit <strong>3<\/strong> (since 3 is less than 4).<\/li>\n\n\n\n<li>Insert <strong>4<\/strong> into the gap right after 3.<\/li>\n\n\n\n<li><strong>Result:<\/strong> <code>[1, 3, 4, 5, 8, 9]<\/code> (<strong>Fully Sorted<\/strong>!)<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">Here is the implementation of <strong>Insertion Sort <\/strong>in <strong>C++<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>#include &lt;iostream&gt;\n#include &lt;vector&gt;\n\n\/\/ Function to perform Insertion Sort\nvoid insertionSort(std::vector&lt;int&gt;&amp; arr) {\n    int n = arr.size();\n    \n    \/\/ Start from the second element (index 1)\n    for (int i = 1; i &lt; n; ++i) {\n        int key = arr&#91;i]; \/\/ The element we are currently positioning\n        int j = i - 1;\n\n        \/\/ Shift elements of arr&#91;0..i-1] that are greater than the key\n        \/\/ to one position ahead of their current position\n        while (j &gt;= 0 &amp;&amp; arr&#91;j] &gt; key) {\n            arr&#91;j + 1] = arr&#91;j];\n            j = j - 1;\n        }\n        \n        \/\/ Insert the key into its correct sorted position\n        arr&#91;j + 1] = key;\n    }\n}\n\n\/\/ Helper function to print the array\nvoid printArray(const std::vector&lt;int&gt;&amp; arr) {\n    for (int num : arr) {\n        std::cout &lt;&lt; num &lt;&lt; \" \";\n    }\n    std::cout &lt;&lt; \"\\n\";\n}\n\nint main() {\n    \/\/ 6-digit array from our step-by-step example\n    std::vector&lt;int&gt; arr = {8, 3, 1, 9, 5, 4};\n\n    std::cout &lt;&lt; \"Original array: \";\n    printArray(arr);\n\n    insertionSort(arr);\n\n    std::cout &lt;&lt; \"Sorted array:   \";\n    printArray(arr);\n\n    return 0;\n}<\/strong><\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">This will sort the array, in <strong>Ascending Order<\/strong>.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\">But what will be the code in <strong>Descending Order<\/strong>? Like almost other sorting techniques, there is just another slight change!<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code><strong>\/\/ Change this:\nwhile (j &gt;= 0 &amp;&amp; arr&#91;j] &gt; key)\n\n\/\/ To this:\nwhile (j &gt;= 0 &amp;&amp; arr&#91;j] &lt; key)<\/strong><\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<h3 class=\"wp-block-heading\">What are Insertion Sort&#8217;s Advantages?<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Extremely Memory-Efficient (O(1) Space):<\/strong> It is a strictly <strong>in-place<\/strong> algorithm. It rearranges the elements directly within the original array, requiring no extra helper arrays. This makes it ideal for systems with very limited RAM (like embedded systems or microcontrollers).<\/li>\n\n\n\n<li><strong>Highly Adaptive (Super Fast for &#8220;Nearly Sorted&#8221; Data):<\/strong> If the input data is already sorted, or almost sorted, Insertion Sort runs in linear time <strong>O(n)<\/strong>. It quickly checks the elements and does virtually no shifting.<\/li>\n\n\n\n<li><strong>The Micro-Scale Champion:<\/strong> Because it has no complex recursion or partition overhead, it is incredibly fast for <strong>small datasets<\/strong> (typically fewer than 15 elements). It easily beats heavy-duty algorithms like <strong>Merge Sort<\/strong> or <strong>Quick Sort<\/strong> on this scale.<\/li>\n\n\n\n<li><strong>Online Sorting Capability:<\/strong> It can sort data in real-time as it arrives. If you are streaming data, you can insert new elements one by one directly into the already-sorted portion without having to restart the sorting process.<\/li>\n\n\n\n<li><strong>Perfect Stability:<\/strong> It is a stable sort, meaning it preserves the original relative order of duplicate elements. This is crucial when sorting database records by multiple criteria.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\">Similarly, It&#8217;s disadvantages include-<\/h3>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>Terrible Scalability (O(<\/strong><math data-latex=\"n^2\"><semantics><msup><mi>n<\/mi><mn>2<\/mn><\/msup><annotation encoding=\"application\/x-tex\">n^2<\/annotation><\/semantics><\/math><strong>) Worst\/Average Case):<\/strong> Because of its quadratic time complexity, its performance plummets drastically as the dataset grows. Sorting 10,000 elements will take millions of operations, making it entirely useless for large-scale data.<\/li>\n\n\n\n<li><strong>Brutal on Reverse-Sorted Data:<\/strong> If you feed it a list that is in absolute reverse order, it suffers its absolute worst-case performance. It is forced to compare and shift every single element all the way back to the beginning of the array on every single pass.<\/li>\n\n\n\n<li><strong>Excessive Writing\/Shifting Operations:<\/strong> Unlike <strong>Selection Sort <\/strong>(which only makes a maximum of O(n) swaps), Insertion Sort has to constantly shift elements over one by one to make room for the key. If writing to memory is &#8220;expensive&#8221; or slow on your hardware, these constant write operations can bottleneck performance.<\/li>\n<\/ol>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n\n\n\n<p class=\"wp-block-paragraph\">So conclusively, <strong>Use Insertion Sort  if:<\/strong> You are dealing with small arrays, streaming data on the fly, working with nearly-sorted lists, or writing code for a system with strict memory limits, and <strong>Avoid it if:<\/strong> You have a large, unpredictable, or completely randomized dataset where a O(n log n) algorithm like <strong>Merge Sort <\/strong>or <strong>Quick Sort <\/strong>is required.<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Insertion Sort Explained: A Step-by-Step Technical Guide Insertion Sort is an elegant simplicity and practical, real-world utility. What is an [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"disabled","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"categories":[66,49,50],"tags":[59,65,60,53,72,35,56],"class_list":["post-153","post","type-post","status-publish","format-standard","hentry","category-algorithms","category-data-structures","category-sorting","tag-big-o-notation","tag-c","tag-data-structures","tag-dsa","tag-insertion-sort","tag-programming","tag-sorting-algorithms"],"_links":{"self":[{"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/posts\/153","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/comments?post=153"}],"version-history":[{"count":5,"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/posts\/153\/revisions"}],"predecessor-version":[{"id":186,"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/posts\/153\/revisions\/186"}],"wp:attachment":[{"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/media?parent=153"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/categories?post=153"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blog.csfree.org\/index.php\/wp-json\/wp\/v2\/tags?post=153"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}