{"id":69254,"date":"2022-04-21T08:00:18","date_gmt":"2022-04-21T06:00:18","guid":{"rendered":"https:\/\/drafts.code-maze.com\/?p=69254"},"modified":"2022-04-21T08:01:54","modified_gmt":"2022-04-21T06:01:54","slug":"insertion-sort-csharp","status":"publish","type":"post","link":"https:\/\/code-maze.com\/insertion-sort-csharp\/","title":{"rendered":"Insertion Sort in C#"},"content":{"rendered":"<p>We have different sorting algorithms that we can use when we want to sort lists of elements. Insertion sort is one of the simplest algorithms that we can use to achieve our goal. In this article, we learn how insertion sort works, implement the algorithm in C#, and analyze its time and space complexity.\u00a0<\/p>\n<div style=\"padding: 20px; border-left: 5px #dc2323 solid; display: block; margin-bottom: 20px; box-shadow: 1px 1px 5px 0px lightgrey;\">To download the source code for this article, you can visit our <a href=\"https:\/\/github.com\/CodeMazeBlog\/CodeMazeGuides\/tree\/main\/csharp-algorithms\/InsertionSort\" target=\"_blank\" rel=\"nofollow noopener\">GitHub repository<\/a>.<\/div>\n<p>Let&#8217;s start.\u00a0<\/p>\n<h2><a id=\"insertion-sort-algorithm\"><\/a>What is Insertion Sort?<\/h2>\n<p>As the name suggests, insertion sort is an algorithm that sorts a list of elements by taking each element and adding it to the correct position in the list. The algorithm iterates through the list until the array is sorted.\u00a0<\/p>\n<p>To understand how insertion sort works, let&#8217;s use the analogy of a card player who wants to sort some playing cards.<\/p>\n<p>The player starts with an empty left hand with all the cards on the table. The empty hand in this case symbolizes an empty array that stores the sorted values.<\/p>\n<p>Then, the player takes one card at a time and places it in the correct position in the left hand. When finding the correct position to place the new card, the player compares the card with the sorted ones in the hand from right to left.\u00a0<\/p>\n<p>Let&#8217;s take a deep dive and have and learn how insertion sort works.\u00a0<\/p>\n<h2><a id=\"how-merge-sort-works\"><\/a>How Does Insertion Sort Algorithm Work?<\/h2>\n<p>To illustrate how the insertion sort algorithm works, let&#8217;s assume we intend to sort this array:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">int[] array = { 86, 13, 60, 46, 73, 52 };<\/code><\/p>\n<p>Assuming 86 is a sorted list of the first item, we are going to compare 86 with 13. Since 13 is less than 86, we switch their positions and the array becomes:<\/p>\n<p><code><span style=\"color: #0000ff;\">13<\/span>, <span style=\"color: #ff6600;\">86<\/span>, 60, 46, 73, 52<\/code><\/p>\n<p>86 is greater than 60 so we switch their positions and the array becomes:<\/p>\n<p><code><span style=\"color: #0000ff;\">13<\/span>, <span style=\"color: #0000ff;\">60<\/span>, <span style=\"color: #ff6600;\">86<\/span>, 46, 73, 52<\/code><\/p>\n<p>86 is greater than 46, hence we shift 86 to the right:<\/p>\n<p><code><span style=\"color: #0000ff;\">13<\/span>, <span style=\"color: #0000ff;\">60<\/span>, <span style=\"color: #ff6600;\">46<\/span>, <span style=\"color: #ff6600;\">86<\/span>, 73, 52<\/code><\/p>\n<p>60 is greater than 46 while 46 is less than 13, so we shift 60 to the right:\u00a0<\/p>\n<p><code><span style=\"color: #0000ff;\">13<\/span>, <span style=\"color: #0000ff;\">46<\/span>, <span style=\"color: #0000ff;\">60<\/span>, <span style=\"color: #ff6600;\">86<\/span>, 73, 52<\/code><\/p>\n<p>86 is greater than 73 and 73 is greater than 60, so we are going to shift 86 to the right:<\/p>\n<p><code><span style=\"color: #0000ff;\">13<\/span>, <span style=\"color: #0000ff;\">46<\/span>, <span style=\"color: #0000ff;\">60<\/span>, <span style=\"color: #0000ff;\">73<\/span>, <span style=\"color: #ff6600;\">86<\/span>, 52<\/code><\/p>\n<p>86 is greater than 52 so we shift it to the right:<\/p>\n<p><code><span style=\"color: #0000ff;\">13<\/span>, <span style=\"color: #0000ff;\">46<\/span>, <span style=\"color: #0000ff;\">60<\/span>, <span style=\"color: #0000ff;\">73<\/span>, 52, <span style=\"color: #ff6600;\">86<\/span><\/code><\/p>\n<p>73 is greater than 52 so we shift it to the right:<\/p>\n<p><code><span style=\"color: #0000ff;\">13<\/span>, <span style=\"color: #0000ff;\">46<\/span>, <span style=\"color: #0000ff;\">60<\/span>, 52, <span style=\"color: #0000ff;\">73<\/span>, <span style=\"color: #ff6600;\">86<\/span><\/code><\/p>\n<p>52 is less than 60 while it&#8217;s greater than 46, hence we switch 52 and 60 to complete the sorting process:\u00a0<\/p>\n<p><code><span style=\"color: #0000ff;\">13<\/span>, <span style=\"color: #0000ff;\">46<\/span>, <span style=\"color: #0000ff;\">52,<\/span> <span style=\"color: #0000ff;\">60<\/span>, <span style=\"color: #0000ff;\">73<\/span>, <span style=\"color: #0000ff;\">86<\/span><\/code><\/p>\n<p>In summary, we can see that insertion sort uses this working principle:<\/p>\n<ol>\n<li>First, compare the current element with its adjacent element.<\/li>\n<li>In case we find a position in the ordered array where we can insert the current element, we create space by shifting the elements to right and inserting the current element at the correct position.<\/li>\n<li>Repeat steps 1 and 2 until the last element in the unsorted array is placed in its correct position.<\/li>\n<\/ol>\n<h2><a id=\"implementation\"><\/a>How to Implement Insertion Sort in C#?<\/h2>\n<p>We can implement the insertion sort algorithm recursively or through an imperative approach.\u00a0<\/p>\n<p>Let&#8217;s start with the imperative approach.<\/p>\n<h3><a id=\"imperative-implementation\"><\/a>Imperative Implementation<\/h3>\n<p>We are going to define a method <code>SortArray()<\/code> as our entry point into the sorting algorithm. The method takes <code>int[] array<\/code> and <code>int length<\/code> as inputs:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public int[] SortArray(int[] array, int length)\r\n{\r\n    for (int i = 1; i &lt; length; i++)\r\n    {\r\n        var key = array[i];\r\n        var flag = 0;\r\n\r\n        for (int j = i - 1; j &gt;= 0 &amp;&amp; flag != 1;)\r\n        {\r\n            if (key &lt; array[j])\r\n            {\r\n                array[j + 1] = array[j];\r\n                j--;\r\n                array[j + 1] = key;\r\n            }\r\n            else flag = 1;\r\n        }\r\n    }\r\n\r\n    return array;\r\n}<\/pre>\n<p><code>SortArray()<\/code> uses two nested loops to sort the array elements. We can see that the iteration process starts from the second element\u00a0<code>i = 1<\/code>.<\/p>\n<p>We have to assume that the array is logically divided into two segments with the left segment holding sorted elements while the right segment holding unsorted array elements.\u00a0<\/p>\n<p>For each pass of the outer loop, the current element <code>key = array[i]<\/code> is inserted into its correct position in the array. The inner loop checks if the current element is less than, which is the last element in the sorted segment of the array. If <code>key &lt; array[j]<\/code>\u00a0is true, we shift their positions, otherwise, we set the <code>flag<\/code> variable to 1 to allow the outer loop to iterate:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">for (int j = i - 1; j &gt;= 0 &amp;&amp; flag != 1;)\r\n{\r\n    if (key &lt; array[j])\r\n    {\r\n        array[j + 1] = array[j];\r\n        j--;\r\n        array[j + 1] = key;\r\n    }\r\n    else flag = 1;\r\n}<\/pre>\n<p>This process is done iteratively until the array is sorted.\u00a0<\/p>\n<p data-enlighter-language=\"csharp\">Finally, we can verify that the <code>SortArray()<\/code> method sorts a given unsorted array accurately:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var array = new int[] { 73, 57, 49, 99, 133, 20, 1 };\r\nvar expected = new int[] { 1, 20, 49, 57, 73, 99, 133 };\r\nvar sortFunction = new InsertionSortMethods();\r\n\r\nvar sortedArray = sortFunction.SortArray(array, array.Length);\r\n\r\nAssert.IsNotNull(sortedArray);\r\nCollectionAssert.AreEqual(sortedArray, expected);<\/pre>\n<h3><a id=\"recursive-implementation\"><\/a>Recursive Implementation<\/h3>\n<p class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">We are going to define a method <code>SortArrayRecursive()<\/code> that takes <code>array<\/code> and <code>length<\/code> as inputs:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public int[] SortArrayRecursive(int[] array, int length) \r\n{\r\n    if (length &lt;= 1)\r\n    {\r\n        return array;\r\n    }\r\n\r\n    SortArrayRecursive(array, length - 1);\r\n    var key = array[length - 1];\r\n    var k = length - 2;\r\n\r\n    while (k &gt;= 0 &amp;&amp; array[k] &gt; key)\r\n    {\r\n        array[k + 1] = array[k];\r\n        k = k - 1;\r\n    }\r\n\r\n    array[k + 1] = key;\r\n\r\n    return array;\r\n}<\/pre>\n<p>We start by checking whether we are attempting to sort an array that contains a single element as our base case here:\u00a0<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">if (length &lt;= 1)\r\n{\r\n    return array;\r\n}<\/pre>\n<p>If the base-case scenario is not true, <code>SortArrayRecursive()<\/code> calls itself while passing the <code>array<\/code> and <code>length -1<\/code> as its parameters.\u00a0<\/p>\n<p>To hold the value of the last element in the sorted subarray ( <code>array[length - 1]<\/code>), we assign it to <code>key<\/code> . <code>k<\/code> holds the second last element of the array, which we are going to compare against <code>key<\/code>.\u00a0<\/p>\n<p>Next, we are going to iterate through the array while comparing <code>k<\/code> it with <code>key<\/code> . We shift their positions if <code>k<\/code> are greater than <code>key<\/code>:\u00a0<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">while (k &gt;= 0 &amp;&amp; array[k] &gt; key)\r\n{\r\n    array[k + 1] = array[k];\r\n    k = k - 1;\r\n}<\/pre>\n<p>Finally, we can verify that the <code>SortArrayRecursive()<\/code> method sorts a given unsorted array accurately:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var array = new int[] { 73, 57, 49, 99, 133, 20, 1 };\r\nvar expected = new int[] { 1, 20, 49, 57, 73, 99, 133 };\r\nvar sortFunction = new InsertionSortMethods();\r\n\r\nvar sortedArray = sortFunction.SortArrayRecursive(array, array.Length);\r\n\r\nAssert.IsNotNull(sortedArray);\r\nCollectionAssert.AreEqual(sortedArray, expected);<\/pre>\n<h2><a id=\"time-complexity\"><\/a>Space and Time Complexity of Insertion Sort Algorithm<\/h2>\n<p>As we&#8217;ve seen in the <a href=\"#implementation\">implementation<\/a> section, the insertion sort algorithm sorts all the elements in place. Therefore, the space complexity of insertion sort is <strong>O(1)<\/strong>.\u00a0<\/p>\n<h3><a id=\"best-case\"><\/a>Best-Case Time Complexity<\/h3>\n<p>Insertion sort encounters the best-case time complexity scenario when we attempt to sort an array that is already sorted. In this case, the algorithm is going to compare each array element to its predecessor. Assuming the size of the array is N, the algorithm will take N steps to sort the array.\u00a0<\/p>\n<p>Therefore, the best-case time complexity of insertion sort is <strong>O(N)<\/strong>.\u00a0<\/p>\n<h3><a id=\"average-case\"><\/a>Average-Case Time Complexity<\/h3>\n<p>When insertion sort encounters random array elements it encounters an average-case time complexity scenario. The algorithm compares each array element to its predecessor and finding the correct position to place elements would take <strong>O(N<sup>2<\/sup>)<\/strong>.\u00a0<\/p>\n<h3><a id=\"worst-case\"><\/a>Worst-Case Time Complexity<\/h3>\n<p>This scenario occurs when insertion sort encounters a reversed list. The algorithm inserts every array element at the beginning of the sorted subarray, which makes it have a time complexity of\u00a0 <strong>O(N<sup>2<\/sup>).<\/strong><\/p>\n<h2><a id=\"benefits\"><\/a>Advantages of Insertion Sort Algorithm<\/h2>\n<p>To start with, it is simple to learn and use, which makes it easy to implement.\u00a0<\/p>\n<p>Besides being simple to implement, insertion sort is effective when used in memory-intensive applications as it does not require a lot of additional memory.\u00a0<\/p>\n<p>Insertion sort maintains the relative order of the array elements in case it encounters two similar values (stable), unlike <a href=\"https:\/\/code-maze.com\/csharp-quicksort-algorithm\/\">quicksort<\/a>, which is unstable.\u00a0<\/p>\n<h2><a id=\"disadvantages\"><\/a>Disadvantages of Insertion Sort Algorithm<\/h2>\n<p>We have learned that insertion sort has an <a href=\"#average-case\">average-case<\/a> and <a href=\"#worst-case\">worst-case complexity<\/a> of <strong>O(N<sup>2<\/sup>).\u00a0<\/strong>This makes the algorithm less efficient when compared to algorithms such as <a href=\"https:\/\/code-maze.com\/csharp-quicksort-algorithm\/\" target=\"_blank\" rel=\"noopener\">quicksort<\/a> and <a href=\"https:\/\/code-maze.com\/csharp-merge-sort\/\" target=\"_blank\" rel=\"noopener\">merge sort<\/a>.\u00a0<\/p>\n<h2><a id=\"performance\"><\/a>Performance Tests<\/h2>\n<p>Let&#8217;s assess how insertion sort performs by measuring the time it takes for it to sort an array.\u00a0For these tests, we are going to measure both the <a href=\"#imperative-implementation\">imperative<\/a> and <a href=\"#recursive-implementation\">recursive implementations<\/a> of the insertion sort algorithm.\u00a0\u00a0<\/p>\n<p>First, let&#8217;s write a method to generate a set of random array elements:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public static int[] CreateRandomArray(int size)\r\n{\r\n    var array = new int[size];\r\n    var rand = new Random();\r\n\r\n    for (int i = 0; i &lt; size; i++)\r\n        array[i] = rand.Next();\r\n\r\n    return array;\r\n}<\/pre>\n<p>The <code>CreateRandomArray()<\/code> the method takes an integer as its sole input. Using the inbuilt <code>Random<\/code> class, we generate integer values that we&#8217;re going to put into the array.<\/p>\n<p>Next, we are going to define a method that generates a sequence of elements. This method simulates a scenario where we have a sorted array:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public static int[] CreateSortedArray(int size)\r\n{\r\n    var array = new int[size];\r\n\r\n    for (int i = 0; i &lt; size; i++)\r\n        array[i] = i;\r\n\r\n    return array;\r\n}<\/pre>\n<p data-enlighter-language=\"csharp\">To make the tests as realistic as possible, we are going to use the inbuilt class <code>Array.Reverse()<\/code> to reverse the arrays generated from the <code>CreateSortedArray()<\/code> method.\u00a0<\/p>\n<p data-enlighter-language=\"csharp\">We can create a simple method <code>CreateReversedArray()<\/code> that takes an <code>int[] array<\/code> as its sole parameter and returns a reversed array:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public static int[] CreateReversedArray(int[] array)\r\n{\r\n    Array.Reverse(array);\r\n\r\n    return array;\r\n}<\/pre>\n<p data-enlighter-language=\"csharp\">Next, we are going to create an object that holds different arrays that have random and sorted values:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public IEnumerable&lt;object[]&gt; SampleArrays()\r\n{\r\n    yield return new object[] { CreateRandomArray(200), 200, \"Small Unsorted\" };\r\n    yield return new object[] { CreateRandomArray(2000), 2000, \"Medium Unsorted\" };\r\n    yield return new object[] { CreateRandomArray(20000), 20000, \"Large Unsorted\" };\r\n    yield return new object[] { CreateSortedArray(200), 200, \"Small Sorted\" };\r\n    yield return new object[] { CreateSortedArray(2000), 2000, \"Medium Sorted\" };\r\n    yield return new object[] { CreateSortedArray(20000), 20000, \"Large Sorted\" };\r\n    yield return new object[] { CreateReversedArray(CreateSortedArray(200)), 200, \"Small Reversed\" };\r\n    yield return new object[] { CreateReversedArray(CreateSortedArray(2000)), 2000, \"Medium Reversed\" };\r\n    yield return new object[] { CreateReversedArray(CreateSortedArray(20000)), 20000, \"Large Reversed\" };\r\n}<\/pre>\n<p>Each object entry has three values: an integer array e.g.\u00a0 <code>CreateRandomArray(200)<\/code>, its length (200), and a string object storing the name of that array (&#8220;Small Unsorted&#8221;).\u00a0<\/p>\n<p>The array objects have different sizes (to simulate time complexity scenarios) and hold <a href=\"https:\/\/code-maze.com\/csharp-generate-random-numbers-range\/\" target=\"_blank\" rel=\"noopener\">random numbers<\/a> that are added by the <code>CreateRandomArray()<\/code> method.<\/p>\n<p>The <code>CreateSortedArray()<\/code> the method creates arrays that have values that are sorted. On the other hand, <code>CreateReversedArray()<\/code>creates reverses a sorted array to simulate <a href=\"#worst-case\">worst-case complexity<\/a> scenarios.\u00a0<\/p>\n<p>Let&#8217;s assess the sample best, average, and worst-case complexity performance results of the algorithm:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">|             Method |        array | length |       arrayName |         Mean |       Error |       StdDev |\r\n|------------------- |------------- |------- |---------------- |-------------:|------------:|-------------:|\r\n|          SortArray |   Int32[200] |    200 |  Small Reversed |     403.4 ns |     7.89 ns |      9.39 ns |\r\n| SortArrayRecursive |   Int32[200] |    200 |  Small Reversed |   1,055.7 ns |    21.12 ns |     41.69 ns |\r\n|          SortArray |   Int32[200] |    200 |    Small Sorted |     400.2 ns |     7.72 ns |      6.84 ns |\r\n| SortArrayRecursive |   Int32[200] |    200 |    Small Sorted |   1,022.0 ns |    18.79 ns |     15.69 ns |\r\n|          SortArray |   Int32[200] |    200 |  Small Unsorted |     398.9 ns |     7.62 ns |      5.95 ns |\r\n| SortArrayRecursive |   Int32[200] |    200 |  Small Unsorted |   1,031.8 ns |    19.95 ns |     24.50 ns |\r\n|          SortArray |  Int32[2000] |   2000 | Medium Reversed |   3,849.0 ns |    76.73 ns |     88.36 ns |\r\n| SortArrayRecursive |  Int32[2000] |   2000 | Medium Reversed |  12,186.8 ns |   240.80 ns |    395.64 ns |\r\n|          SortArray |  Int32[2000] |   2000 |   Medium Sorted |   3,850.5 ns |    73.60 ns |     78.75 ns |\r\n| SortArrayRecursive |  Int32[2000] |   2000 |   Medium Sorted |  12,077.7 ns |   240.66 ns |    286.49 ns |\r\n|          SortArray |  Int32[2000] |   2000 | Medium Unsorted |   3,958.1 ns |    77.61 ns |    211.15 ns |\r\n| SortArrayRecursive |  Int32[2000] |   2000 | Medium Unsorted |  13,002.4 ns |   577.56 ns |  1,666.39 ns |\r\n|          SortArray | Int32[20000] |  20000 |  Large Reversed |  59,549.5 ns | 4,488.07 ns | 13,020.71 ns |\r\n| SortArrayRecursive | Int32[20000] |  20000 |  Large Reversed | 160,805.7 ns | 3,094.82 ns |  3,800.72 ns |\r\n|          SortArray | Int32[20000] |  20000 |    Large Sorted |  36,877.7 ns |   681.48 ns |    669.31 ns |\r\n| SortArrayRecursive | Int32[20000] |  20000 |    Large Sorted | 156,821.2 ns | 2,280.12 ns |  1,780.17 ns |\r\n|          SortArray | Int32[20000] |  20000 |  Large Unsorted |  36,467.7 ns |   483.45 ns |    452.22 ns |\r\n| SortArrayRecursive | Int32[20000] |  20000 |  Large Unsorted | 158,289.3 ns | 2,164.03 ns |  1,807.06 ns |<\/pre>\n<p><code>SortArrayRecursive()<\/code> is at least two times slower than the imperative implementation <code>SortArray()<\/code> in all cases. For example, when sorting a small reversed array, <code>SortArrayRecursive()<\/code> takes approximately 1,056 ns while <code>SortArray()<\/code> takes about 404 ns.<\/p>\n<p>The\u00a0<a href=\"#recursive-implementation\">recursive implementation<\/a> of the insertion sort algorithm is slower than its <a href=\"#imperative-implementation\">imperative implementation<\/a> in C# as it requires the allocation of a new stack frame every time <code>SortArrayRecursive()<\/code> calls itself.\u00a0\u00a0<\/p>\n<p>From the benchmark, we can also see that the algorithm takes longer to sort reversed arrays, which simulates the algorithm&#8217;s <a href=\"#worst-case\">worst-case complexity<\/a>. Let&#8217;s analyze the results obtained from sorting the largest array consisting of 20,000 elements. <code>SortArray()<\/code> takes almost twice as long to sort a reversed array (59,549.5 ns) as compared to sorting a randomized array (36,467.7 ns).<\/p>\n<h2><a id=\"conclusion\"><\/a>Conclusion<\/h2>\n<p>In this article, we have learned how insertion sort in C# works. It is simple to implement and use but it is not efficient.\u00a0<\/p>\n","protected":false},"excerpt":{"rendered":"<p>We have different sorting algorithms that we can use when we want to sort lists of elements. Insertion sort is one of the simplest algorithms that we can use to achieve our goal. In this article, we learn how insertion sort works, implement the algorithm in C#, and analyze its time and space complexity.\u00a0 Let&#8217;s [&hellip;]<\/p>\n","protected":false},"author":6,"featured_media":62189,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_et_pb_use_builder":"","_et_pb_old_content":"","_et_gb_content_width":"","footnotes":""},"categories":[1010,12],"tags":[1140,1218,1219,592,1141],"class_list":["post-69254","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-algorithm","category-csharp","tag-algorithm","tag-insertion-c","tag-insertion-sort","tag-sorting","tag-sorting-algorithm","et-has-post-format-content","et_post_format-et-post-format-standard"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v24.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Insertion Sort in C# - Code Maze<\/title>\n<meta name=\"description\" content=\"Insertion sort is one of the simplest algorithms that we can use to sort an array. Let&#039;s implement it in C#.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/code-maze.com\/insertion-sort-csharp\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Insertion Sort in C# - Code Maze\" \/>\n<meta property=\"og:description\" content=\"Insertion sort is one of the simplest algorithms that we can use to sort an array. Let&#039;s implement it in C#.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/code-maze.com\/insertion-sort-csharp\/\" \/>\n<meta property=\"og:site_name\" content=\"Code Maze\" \/>\n<meta property=\"article:published_time\" content=\"2022-04-21T06:00:18+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-04-21T06:01:54+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\" \/>\n\t<meta property=\"og:image:width\" content=\"1100\" \/>\n\t<meta property=\"og:image:height\" content=\"620\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Code Maze\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@https:\/\/twitter.com\/CodeMazeBlog\" \/>\n<meta name=\"twitter:site\" content=\"@CodeMazeBlog\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Code Maze\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"11 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":[\"Article\",\"BlogPosting\"],\"@id\":\"https:\/\/code-maze.com\/insertion-sort-csharp\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/insertion-sort-csharp\/\"},\"author\":{\"name\":\"Code Maze\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\"},\"headline\":\"Insertion Sort in C#\",\"datePublished\":\"2022-04-21T06:00:18+00:00\",\"dateModified\":\"2022-04-21T06:01:54+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/code-maze.com\/insertion-sort-csharp\/\"},\"wordCount\":1412,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/insertion-sort-csharp\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"keywords\":[\"algorithm\",\"insertion C#\",\"insertion sort\",\"sorting\",\"sorting algorithm\"],\"articleSection\":[\"Algorithm\",\"C#\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/code-maze.com\/insertion-sort-csharp\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/code-maze.com\/insertion-sort-csharp\/\",\"url\":\"https:\/\/code-maze.com\/insertion-sort-csharp\/\",\"name\":\"Insertion Sort in C# - Code Maze\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/code-maze.com\/insertion-sort-csharp\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/insertion-sort-csharp\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"datePublished\":\"2022-04-21T06:00:18+00:00\",\"dateModified\":\"2022-04-21T06:01:54+00:00\",\"description\":\"Insertion sort is one of the simplest algorithms that we can use to sort an array. Let's implement it in C#.\",\"breadcrumb\":{\"@id\":\"https:\/\/code-maze.com\/insertion-sort-csharp\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/code-maze.com\/insertion-sort-csharp\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/insertion-sort-csharp\/#primaryimage\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"width\":1100,\"height\":620,\"caption\":\"C# Development\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/code-maze.com\/insertion-sort-csharp\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/code-maze.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Insertion Sort in C#\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/code-maze.com\/#website\",\"url\":\"https:\/\/code-maze.com\/\",\"name\":\"Code Maze\",\"description\":\"Learn. Code. Succeed.\",\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/code-maze.com\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/code-maze.com\/#organization\",\"name\":\"Code Maze\",\"url\":\"https:\/\/code-maze.com\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png\",\"width\":3511,\"height\":3510,\"caption\":\"Code Maze\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/CodeMazeBlog\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\",\"name\":\"Code Maze\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"contentUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png\",\"caption\":\"Code Maze\"},\"description\":\"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.\",\"sameAs\":[\"https:\/\/www.linkedin.com\/company\/codemaze\/\",\"https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog\"],\"url\":\"https:\/\/code-maze.com\/author\/codemazecontributor\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Insertion Sort in C# - Code Maze","description":"Insertion sort is one of the simplest algorithms that we can use to sort an array. Let's implement it in C#.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/code-maze.com\/insertion-sort-csharp\/","og_locale":"en_US","og_type":"article","og_title":"Insertion Sort in C# - Code Maze","og_description":"Insertion sort is one of the simplest algorithms that we can use to sort an array. Let's implement it in C#.","og_url":"https:\/\/code-maze.com\/insertion-sort-csharp\/","og_site_name":"Code Maze","article_published_time":"2022-04-21T06:00:18+00:00","article_modified_time":"2022-04-21T06:01:54+00:00","og_image":[{"width":1100,"height":620,"url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","type":"image\/png"}],"author":"Code Maze","twitter_card":"summary_large_image","twitter_creator":"@https:\/\/twitter.com\/CodeMazeBlog","twitter_site":"@CodeMazeBlog","twitter_misc":{"Written by":"Code Maze","Est. reading time":"11 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":["Article","BlogPosting"],"@id":"https:\/\/code-maze.com\/insertion-sort-csharp\/#article","isPartOf":{"@id":"https:\/\/code-maze.com\/insertion-sort-csharp\/"},"author":{"name":"Code Maze","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04"},"headline":"Insertion Sort in C#","datePublished":"2022-04-21T06:00:18+00:00","dateModified":"2022-04-21T06:01:54+00:00","mainEntityOfPage":{"@id":"https:\/\/code-maze.com\/insertion-sort-csharp\/"},"wordCount":1412,"commentCount":0,"publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"image":{"@id":"https:\/\/code-maze.com\/insertion-sort-csharp\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","keywords":["algorithm","insertion C#","insertion sort","sorting","sorting algorithm"],"articleSection":["Algorithm","C#"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/code-maze.com\/insertion-sort-csharp\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/code-maze.com\/insertion-sort-csharp\/","url":"https:\/\/code-maze.com\/insertion-sort-csharp\/","name":"Insertion Sort in C# - Code Maze","isPartOf":{"@id":"https:\/\/code-maze.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/code-maze.com\/insertion-sort-csharp\/#primaryimage"},"image":{"@id":"https:\/\/code-maze.com\/insertion-sort-csharp\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","datePublished":"2022-04-21T06:00:18+00:00","dateModified":"2022-04-21T06:01:54+00:00","description":"Insertion sort is one of the simplest algorithms that we can use to sort an array. Let's implement it in C#.","breadcrumb":{"@id":"https:\/\/code-maze.com\/insertion-sort-csharp\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/code-maze.com\/insertion-sort-csharp\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/insertion-sort-csharp\/#primaryimage","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","width":1100,"height":620,"caption":"C# Development"},{"@type":"BreadcrumbList","@id":"https:\/\/code-maze.com\/insertion-sort-csharp\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/code-maze.com\/"},{"@type":"ListItem","position":2,"name":"Insertion Sort in C#"}]},{"@type":"WebSite","@id":"https:\/\/code-maze.com\/#website","url":"https:\/\/code-maze.com\/","name":"Code Maze","description":"Learn. Code. Succeed.","publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/code-maze.com\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Organization","@id":"https:\/\/code-maze.com\/#organization","name":"Code Maze","url":"https:\/\/code-maze.com\/","logo":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez.png","width":3511,"height":3510,"caption":"Code Maze"},"image":{"@id":"https:\/\/code-maze.com\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/CodeMazeBlog"]},{"@type":"Person","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04","name":"Code Maze","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/#\/schema\/person\/image\/","url":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","contentUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2020\/01\/Code-Maze-Only-Logo-Transparent-HRez-150x150.png","caption":"Code Maze"},"description":"This is the standard author on the site. Most articles are published by individual authors, with their profiles, but when several authors have contributed, we publish collectively as a part of this profile.","sameAs":["https:\/\/www.linkedin.com\/company\/codemaze\/","https:\/\/x.com\/https:\/\/twitter.com\/CodeMazeBlog"],"url":"https:\/\/code-maze.com\/author\/codemazecontributor\/"}]}},"_links":{"self":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/69254","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/users\/6"}],"replies":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/comments?post=69254"}],"version-history":[{"count":5,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/69254\/revisions"}],"predecessor-version":[{"id":69533,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/69254\/revisions\/69533"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media\/62189"}],"wp:attachment":[{"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/media?parent=69254"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/categories?post=69254"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/tags?post=69254"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}