{"id":69957,"date":"2022-05-31T08:00:59","date_gmt":"2022-05-31T06:00:59","guid":{"rendered":"https:\/\/drafts.code-maze.com\/?p=69957"},"modified":"2022-06-05T13:40:16","modified_gmt":"2022-06-05T11:40:16","slug":"bucket-sort-csharp","status":"publish","type":"post","link":"https:\/\/code-maze.com\/bucket-sort-csharp\/","title":{"rendered":"Bucket Sort in C#"},"content":{"rendered":"<p>Sorting is one of the most common programming problems that we have to solve. The good news is, that there are many sorting algorithms available to address such problems. However, each algorithm has its strengths and weaknesses, which may influence the choice of algorithm to use in different scenarios.<\/p>\n<p>In this article, we&#8217;re going to learn about bucket sort, see how it works, implement it in C# and analyze its time and space complexity.<\/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\/BucketSort\" target=\"_blank\" rel=\"nofollow noopener\">GitHub repository<\/a>.<\/div>\n<p>Let&#8217;s start.\u00a0<\/p>\n<h2><a id=\"bucket-sort-algorithm\"><\/a>What Is Bucket Sort?<\/h2>\n<p><strong>Bucket\/bin sort is a sorting algorithm that works by partitioning an array into several buckets.<\/strong> The bucket sort algorithm then sorts the contents of each bucket recursively or by applying different sorting algorithms.\u00a0<\/p>\n<p>Bucket sort uses this principle to sort a list of elements:<\/p>\n<ul>\n<li>The algorithm sets up an array of empty buckets<\/li>\n<li>Each object from the unsorted array is scattered into its corresponding buckets<\/li>\n<li>Each bucket gets sorted individually<\/li>\n<li>Sorted items are gathered from each bucket in their correct order<\/li>\n<\/ul>\n<p>Let&#8217;s take a deep dive and learn how bucket sort works.\u00a0<\/p>\n<h2><a id=\"how-bucket-sort-works\"><\/a>How Does Bucket Sort Algorithm Work?<\/h2>\n<p>To illustrate how the bucket 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 = {42, 6, 16, 4, 12, 24, 46, 17};<\/code><\/p>\n<p>We need to divide these elements into buckets using an identifier. To make our example simple, let&#8217;s create buckets based on a range of ten values for each bucket:\u00a00 &#8211; 9,\u00a010 &#8211; 19,\u00a020 &#8211; 29, 30 &#8211; 39, and 40 &#8211; 49.<\/p>\n<p>Next, we are going to &#8220;scatter&#8221; the elements into those buckets based on their range:\u00a0<\/p>\n<ul>\n<li><strong>0 &#8211; 9:<\/strong> 6, 4<\/li>\n<li><strong>10 &#8211; 19:<\/strong> 16, 12, 17<\/li>\n<li><strong>20 &#8211; 29:<\/strong> 24<\/li>\n<li><strong>30 &#8211; 39:<\/strong> null<\/li>\n<li><strong>40 &#8211; 49:<\/strong> 42, 56<\/li>\n<\/ul>\n<p>Now, we sort the items in each bucket using a different algorithm such as <a href=\"https:\/\/code-maze.com\/csharp-bubble-sort\/\" target=\"_blank\" rel=\"noopener\">bubble sort<\/a> (to keep our illustration simple):<\/p>\n<ul>\n<li><strong>0 &#8211; 9:<\/strong> 4, 6<\/li>\n<li><strong>10 &#8211; 19:<\/strong> 12, 16, 17<\/li>\n<li><strong>20 &#8211; 29:<\/strong> 24<\/li>\n<li><strong>30 &#8211; 39:<\/strong> null<\/li>\n<li><strong>40 &#8211; 49:<\/strong> 42, 56<\/li>\n<\/ul>\n<p>Finally, we gather the items from each bucket in the correct order, which completes the sorting process:\u00a0<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"raw\">4, 6, 12, 16, 17, 24, 42, 56<\/code><\/p>\n<p>Let&#8217;s learn how to implement the bucket sort algorithm in C#.<\/p>\n<h2><a id=\"implementation\"><\/a>How to Implement Bucket Sort in C#?<\/h2>\n<p>We can implement the bucket sort algorithm in different ways. We are going to implement the algorithm in C# as we have discussed so far and try to improve its shortcomings by implementing an optimized solution.<\/p>\n<h3><a id=\"non-optimized-solution\"><\/a>Non-Optimized Bucket Sort Implementation in C#<\/h3>\n<p>First, we are going to write a function <code>int[] BubbleSort<\/code> that takes a <code>List&lt;int&gt;<\/code> object and sorts its values using the <a href=\"https:\/\/code-maze.com\/csharp-bubble-sort\/\" target=\"_blank\" rel=\"noopener\">bubble sort algorithm<\/a>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public static int[] BubbleSort(List&lt;int&gt; listInput)\r\n{\r\n    for (int i = 0; i &lt; listInput.Count; i++)\r\n    {\r\n        for (int j = 0; j &lt; listInput.Count; j++)\r\n        {\r\n            if (listInput[i] &lt; listInput[j])\r\n            {\r\n                var temp = listInput[i];\r\n                listInput[i] = listInput[j];\r\n                listInput[j] = temp;\r\n            }\r\n        }\r\n    }\r\n    \r\n    return listInput.ToArray();\r\n}<\/pre>\n<p>Next, we are going to define a method called <code>SortArray()<\/code> as our entry point into the sorting algorithm. The method takes <code>int[] array<\/code> as its sole input and returns a sorted array:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public int[] SortArray(int[] array)\r\n{\r\n    List&lt;int&gt; sortedList = new List&lt;int&gt;();\r\n    var minValue = array[0];\r\n    var maxValue = array[0];\r\n\r\n    if (array == null || array.Length &lt;= 1)\r\n    {\r\n        return array;\r\n    }\r\n\r\n    for (int i = 1; i &lt; array.Length; i++)\r\n    {\r\n        if (array[i] &gt; maxValue)\r\n            maxValue = array[i];\r\n        if (array[i] &lt; minValue)\r\n            minValue = array[i];\r\n    }\r\n    \r\n    var numberOfBuckets = maxValue - minValue + 1;\r\n    List&lt;int&gt;[] bucket = new List&lt;int&gt;[numberOfBuckets];\r\n\r\n    for (int i = 0; i &lt; numberOfBuckets; i++) \r\n    {\r\n        bucket[i] = new List&lt;int&gt;();\r\n    }\r\n       \r\n    for (int i = 0; i &lt; array.Length; i++)\r\n    {\r\n        var selectedBucket = (array[i] \/ numberOfBuckets);\r\n        bucket[selectedBucket].Add(array[i]);\r\n    }\r\n\r\n    for (int i = 0; i &lt; numberOfBuckets; i++)\r\n    {\r\n        int[] temp = BubbleSort(bucket[i]);\r\n        sortedList.AddRange(temp);\r\n    }\r\n\r\n    return sortedList.ToArray();\r\n}<\/pre>\n<p>Let&#8217;s understand how this method works.<\/p>\n<p>First, we check whether <code>int[] array<\/code> is null or has a single element as our base case and skips the sorting process:\u00a0<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">if (array == null || array.Length &lt;= 1)\r\n{\r\n    return array;\r\n}<\/pre>\n<p>Next, we are going to find the maximum and minimum elements in the array:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">for (int i = 1; i &lt; array.Length; i++)\r\n{\r\n    if (array[i] &gt; maxValue)\r\n    {\r\n        maxValue = array[i];\r\n    }\r\n\r\n    if (array[i] &lt; minValue)\r\n    {\r\n        minValue = array[i];\r\n    }\r\n}<\/pre>\n<p>Here, we loop through the <code>array<\/code> as we find the <code>maxValue<\/code> and <code>minValue<\/code>, which are going to come in handy when we create the buckets, which in this case, are <code>List&lt;int&gt;<\/code> objects:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var numberOfBuckets = maxValue - minValue + 1;\r\nList&lt;int&gt;[] bucket = new List&lt;int&gt;[numberOfBuckets];\r\n\r\nfor (int i = 0; i &lt; numberOfBuckets; i++) \r\n{\r\n    bucket[i] = new List&lt;int&gt;();\r\n}<\/pre>\n<p>Now that we have the buckets ready, we are going to scatter the array values into the buckets we&#8217;ve created:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">for (int i = 0; i &lt; array.Length; i++)\r\n{\r\n    var selectedBucket = (array[i] \/ numberOfBuckets);\r\n    bucket[selectedBucket].Add(array[i]);\r\n}\r\n<\/pre>\n<p>After initializing the buckets, we are going to invoke the <code>BubbleSort()<\/code> method we created earlier and pass each bucket. The method returns a sorted array, which we add at the end of the sorted list:\u00a0<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">for (int i = 0; i &lt; numberOfBuckets; i++)\r\n{\r\n    int[] temp = BubbleSort(bucket[i]);\r\n    sortedList.AddRange(temp);\r\n}\r\n\r\nreturn sortedList.ToArray();<\/pre>\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=\"optimized-solution\"><\/a>Optimized Bucket Sort Implementation in C#<\/h3>\n<p>The bucket sort algorithm has a few weaknesses, which were are going to discuss soon. We can improve the algorithm by initializing the buckets only when we need them, which saves us some time initializing them. Using the <code>LinkedList&lt;T&gt;<\/code> objects instead of <code>List&lt;T&gt;<\/code> would come in handy when accessing sequential data, which can give us a slight performance edge.\u00a0<\/p>\n<p>Let&#8217;s learn how to optimize our current implementation:\u00a0<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public int[] SortArrayOptimized(int[] array)\r\n{\r\n    if (array == null || array.Length &lt;= 1)\r\n    {\r\n        return array;\r\n    }\r\n\r\n    int maxValue = array[0]; \r\n    int minValue = array[0];\r\n\r\n    for (int i = 1; i &lt; array.Length; i++)\r\n    {\r\n        if (array[i] &gt; maxValue)\r\n        {\r\n            maxValue = array[i];\r\n        }\r\n\r\n        if (array[i] &lt; minValue)\r\n        {\r\n            minValue = array[i];\r\n        }\r\n    }\r\n\r\n    LinkedList&lt;int&gt;[] bucket = new LinkedList&lt;int&gt;[maxValue - minValue + 1];\r\n\r\n    for (int i = 0; i &lt; array.Length; i++)\r\n    {\r\n        if (bucket[array[i] - minValue] == null)\r\n        {\r\n            bucket[array[i] - minValue] = new LinkedList&lt;int&gt;();\r\n        }\r\n\r\n        bucket[array[i] - minValue].AddLast(array[i]);\r\n    }\r\n\r\n    var index = 0;\r\n    \r\n    for (int i = 0; i &lt; bucket.Length; i++)\r\n    {\r\n        if (bucket[i] != null)\r\n        {\r\n            LinkedListNode&lt;int&gt; node = bucket[i].First;\r\n\r\n            while (node != null)\r\n            {\r\n                array[index] = node.Value;\r\n                node = node.Next; \r\n                index++;\r\n            }\r\n        }\r\n    }\r\n    \r\n    return array;\r\n}<\/pre>\n<p><code>SortArrayOptimized()<\/code> is similar to <code>SortArray()<\/code> but has a few notable differences such as the use of\u00a0<code>LinkedList&lt;int&gt;<\/code> objects instead of <code>List&lt;int&gt;<\/code> objects:<\/p>\n<p><code class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">LinkedList&lt;int&gt;[] bucket = new LinkedList&lt;int&gt;[maxValue - minValue + 1];<\/code><\/p>\n<p>The goal of this process is to store each array element in its corresponding index and move everything to the left as possible (<code>minValue<\/code>) during the sorting process:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">for (int i = 0; i &lt; array.Length; i++)\r\n{\r\n    if (bucket[array[i] - minValue] == null)\r\n    {\r\n        bucket[array[i] - minValue] = new LinkedList&lt;int&gt;();\r\n    }\r\n\r\n    bucket[array[i] - minValue].AddLast(array[i]);\r\n}<\/pre>\n<p>We can see that a new <code>LinkedList&lt;int&gt;<\/code> object is created when the loop encounters <code>minValue<\/code> in the array and adds the rest of the array elements in order at the end of the bucket when calling <code>bucket[array[i] - minValue].AddLast(array[i])<\/code>.<\/p>\n<p>Next, we start the process of moving the elements from the bucket back into <code>int[] array<\/code>.<\/p>\n<p>We achieve this by setting the index of the array to zero and iterating through the bucket as we add the sorted elements back into <code>int[] array<\/code>:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">var index = 0;\r\n  \r\nfor (int i = 0; i &lt; bucket.Length; i++)\r\n{\r\n    if (bucket[i] != null)\r\n    {\r\n        LinkedListNode&lt;int&gt; node = bucket[i].First;\r\n\r\n        while (node != null)\r\n        {\r\n            array[index] = node.Value; \r\n            node = node.Next; \r\n            index++;\r\n        }\r\n    }\r\n}\r\n \r\nreturn array;<\/pre>\n<p>We start iterating from the head of the <code>LinkedList&lt;int&gt;<\/code> as we move to the next nodes as we add the values to the <code>int[] array<\/code> object.\u00a0The loop terminates when the next node is null and returns the sorted array.\u00a0<\/p>\n<p data-enlighter-language=\"csharp\">Next, we can verify that the <code>SortArray()<\/code>\u00a0 and <code>SortArrayOptimized()<\/code> methods return the same result when sorting an array:<\/p>\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"csharp\">public void GivenUnsortedArray_WhenArrayIsNotEmpty_ThenReturnSortedArray()\r\n{\r\n    var array = new int[] { 73, 57, 49, 99, 133, 20, 1 };\r\n    var expected = new int[] { 1, 20, 49, 57, 73, 99, 133 };\r\n    var sortFunction = new BucketSortMethods();\r\n\r\n    var sortOptimized = sortFunction.SortArrayOptimized(array, string.Empty);\r\n    var sortNormal = sortFunction.SortArray(array, string.Empty);\r\n\r\n \u00a0  CollectionAssert.AreEqual(sortNormal, expected);\r\n    CollectionAssert.AreEqual(sortOptimized, expected); \r\n}<\/pre>\n<h2><a id=\"time-complexity\"><\/a>Space and Time Complexity of Bucket Sort Algorithm<\/h2>\n<p>As we&#8217;ve seen in the <a href=\"#implementation\">implementation<\/a> section, the bucket sort algorithm requires the creation of buckets to hold the array elements during the sorting process. Therefore, the space complexity of bucket sort is <strong>O(n + k)<\/strong>, with n being the number of elements in the array and k being the number of buckets.\u00a0<\/p>\n<h3><a id=\"best-case\"><\/a>Best-Case Time Complexity<\/h3>\n<p>Bucket sort encounters the best-case time complexity scenario when we scatter elements uniformly across the buckets. The time it would take to sort the array is <strong>O(n + k) <\/strong>with n being the number of elements in the array and k being the number of buckets.<\/p>\n<h3><a id=\"average-case\"><\/a>Average-Case Time Complexity<\/h3>\n<p>When bucket sort encounters random array elements it encounters an average-case time complexity scenario. It would take <strong>O(n + k) <\/strong>time to sort the array with n being the number of elements in the array and k being the number of buckets.<\/p>\n<h3><a id=\"worst-case\"><\/a>Worst-Case Time Complexity<\/h3>\n<p><strong>This scenario occurs when bucket sort encounters a reversed list.<\/strong> Depending on the &#8220;inner algorithm&#8221; used such as the <a href=\"https:\/\/code-maze.com\/csharp-bubble-sort\/\" target=\"_blank\" rel=\"noopener\">bubble sort algorithm<\/a>, the algorithm may need to carry out <strong>N<sup>2<\/sup><\/strong> comparisons. Therefore, the bucket sort algorithm has a worst-case complexity of\u00a0 <strong>O(N<sup>2<\/sup>).<\/strong><\/p>\n<h2><a id=\"benefits\"><\/a>Advantages of Bucket Sort Algorithm<\/h2>\n<p>Bucket sort reduces the number of comparisons we make when sorting elements as we distribute them into different buckets and sort each bucket separately.\u00a0<\/p>\n<p><strong>The algorithm can be fast when we scatter elements uniformly across all the buckets.\u00a0<\/strong><\/p>\n<h2><a id=\"disadvantages\"><\/a>Disadvantages of Bucket Sort Algorithm<\/h2>\n<p>It does not sort elements in place like other algorithms such as <a href=\"https:\/\/code-maze.com\/csharp-merge-sort\/\" target=\"_blank\" rel=\"noopener\">merge sort<\/a>, as it needs <strong>O(n + k)\u00a0<\/strong>space.\u00a0<\/p>\n<p>The algorithm has a <a href=\"#worst-case\">worst-case complexity<\/a> of <strong>O(N<sup>2<\/sup>)<\/strong>.<\/p>\n<p><strong>Bucket sort may or may not be stable<\/strong>. A stable sorting algorithm maintains the relative order of the array elements in case it encounters two similar values, unlike <a href=\"https:\/\/code-maze.com\/csharp-quicksort-algorithm\/\" target=\"_blank\" rel=\"noopener\">quicksort<\/a>, which is unstable.<\/p>\n<h2><a id=\"performance\"><\/a>Performance Tests<\/h2>\n<p>Let&#8217;s assess how bucket sort performs by measuring the time it takes for it to sort an array.\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(1, size);\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\">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), \"Small Unsorted\" };\r\n    yield return new object[] { CreateRandomArray(2000), \"Medium Unsorted\" };\r\n    yield return new object[] { CreateRandomArray(20000), \"Large Unsorted\" };\r\n    yield return new object[] { CreateSortedArray(200), \"Small Sorted\" };\r\n    yield return new object[] { CreateSortedArray(2000), \"Medium Sorted\" };\r\n    yield return new object[] { CreateSortedArray(20000), \"Large Sorted\" };\r\n}<\/pre>\n<p>Each object entry has three values: an integer array e.g. <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. On the other hand, the <code>CreateSortedArray()<\/code> method creates arrays that have values that are sorted.\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 |       arrayName |             Mean |          Error |          StdDev |\r\n|------------------- |------------- |---------------- |-----------------:|---------------:|----------------:|\r\n|          SortArray | Int32[20000] |    Large Sorted |   942,629.686 \u03bcs | 17,950.5497 \u03bcs |  21,368.8525 \u03bcs |\r\n| SortArrayOptimized | Int32[20000] |    Large Sorted |     5,730.690 \u03bcs |    176.0321 \u03bcs |     519.0345 \u03bcs |\r\n|          SortArray | Int32[20000] |  Large Unsorted | 1,538,116.280 \u03bcs | 37,973.6267 \u03bcs | 111,966.0951 \u03bcs |\r\n| SortArrayOptimized | Int32[20000] |  Large Unsorted |     5,631.236 \u03bcs |    111.7425 \u03bcs |     220.5689 \u03bcs |\r\n|          SortArray |  Int32[2000] |   Medium Sorted |    12,017.725 \u03bcs |    170.9306 \u03bcs |     159.8886 \u03bcs |\r\n| SortArrayOptimized |  Int32[2000] |   Medium Sorted |       174.385 \u03bcs |      3.0591 \u03bcs |       3.5229 \u03bcs |\r\n|          SortArray |  Int32[2000] | Medium Unsorted |    11,875.260 \u03bcs |    215.5740 \u03bcs |     435.4702 \u03bcs |\r\n| SortArrayOptimized |  Int32[2000] | Medium Unsorted |       168.497 \u03bcs |      5.7366 \u03bcs |      16.6430 \u03bcs |\r\n|          SortArray |   Int32[200] |    Small Sorted |       106.994 \u03bcs |      2.0930 \u03bcs |       4.2281 \u03bcs |\r\n| SortArrayOptimized |   Int32[200] |    Small Sorted |         8.926 \u03bcs |      0.1784 \u03bcs |       0.2615 \u03bcs |\r\n|          SortArray |   Int32[200] |  Small Unsorted |       153.492 \u03bcs |      5.2994 \u03bcs |      15.6255 \u03bcs |\r\n| SortArrayOptimized |   Int32[200] |  Small Unsorted |        10.968 \u03bcs |      0.3958 \u03bcs |       1.1670 \u03bcs |<\/pre>\n<p><strong>The <\/strong><code>SortArrayOptimized()<\/code><strong> method performs at least ten times better than the <\/strong><code>SortArray()<\/code><strong> method when sorting arrays of different sizes<\/strong>\u00a0because the latter uses an inefficient &#8220;inner algorithm.&#8221; The bubble sort algorithm we implement has to perform <strong>N<sup>2 <\/sup><\/strong>comparisons regardless of the arrays&#8217; sizes, which explains why the non-optimized implementation is always slower than the optimized one.\u00a0<\/p>\n<h2><a id=\"conclusion\"><\/a>Conclusion<\/h2>\n<p>In this article, we have learned how bucket sort works in C#. We can use it in scenarios where we have control over the range of values that we intend to sort. However, other algorithms such as <a href=\"https:\/\/code-maze.com\/csharp-merge-sort\/\" target=\"_blank\" rel=\"noopener\">merge sort<\/a> and <a href=\"https:\/\/code-maze.com\/csharp-quicksort-algorithm\/\" target=\"_blank\" rel=\"noopener\">quick sort<\/a> perform much better than bucket sort.\u00a0\u00a0<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Sorting is one of the most common programming problems that we have to solve. The good news is, that there are many sorting algorithms available to address such problems. However, each algorithm has its strengths and weaknesses, which may influence the choice of algorithm to use in different scenarios. In this article, we&#8217;re going to [&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,1275,592,1141],"class_list":["post-69957","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-algorithm","category-csharp","tag-algorithm","tag-bucket-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>Bucket Sort in C# - Code Maze<\/title>\n<meta name=\"description\" content=\"Bucket sort is a sorting algorithm that works by partitioning an array into several buckets. Let&#039;s see how to implement Bucket Sort 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\/bucket-sort-csharp\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Bucket Sort in C# - Code Maze\" \/>\n<meta property=\"og:description\" content=\"Bucket sort is a sorting algorithm that works by partitioning an array into several buckets. Let&#039;s see how to implement Bucket Sort in C#.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/code-maze.com\/bucket-sort-csharp\/\" \/>\n<meta property=\"og:site_name\" content=\"Code Maze\" \/>\n<meta property=\"article:published_time\" content=\"2022-05-31T06:00:59+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2022-06-05T11:40:16+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\/bucket-sort-csharp\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/bucket-sort-csharp\/\"},\"author\":{\"name\":\"Code Maze\",\"@id\":\"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04\"},\"headline\":\"Bucket Sort in C#\",\"datePublished\":\"2022-05-31T06:00:59+00:00\",\"dateModified\":\"2022-06-05T11:40:16+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/code-maze.com\/bucket-sort-csharp\/\"},\"wordCount\":1404,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\/\/code-maze.com\/#organization\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/bucket-sort-csharp\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"keywords\":[\"algorithm\",\"bucket sort\",\"sorting\",\"sorting algorithm\"],\"articleSection\":[\"Algorithm\",\"C#\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\/\/code-maze.com\/bucket-sort-csharp\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/code-maze.com\/bucket-sort-csharp\/\",\"url\":\"https:\/\/code-maze.com\/bucket-sort-csharp\/\",\"name\":\"Bucket Sort in C# - Code Maze\",\"isPartOf\":{\"@id\":\"https:\/\/code-maze.com\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/code-maze.com\/bucket-sort-csharp\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/code-maze.com\/bucket-sort-csharp\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png\",\"datePublished\":\"2022-05-31T06:00:59+00:00\",\"dateModified\":\"2022-06-05T11:40:16+00:00\",\"description\":\"Bucket sort is a sorting algorithm that works by partitioning an array into several buckets. Let's see how to implement Bucket Sort in C#.\",\"breadcrumb\":{\"@id\":\"https:\/\/code-maze.com\/bucket-sort-csharp\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/code-maze.com\/bucket-sort-csharp\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/code-maze.com\/bucket-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\/bucket-sort-csharp\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/code-maze.com\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Bucket 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":"Bucket Sort in C# - Code Maze","description":"Bucket sort is a sorting algorithm that works by partitioning an array into several buckets. Let's see how to implement Bucket Sort 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\/bucket-sort-csharp\/","og_locale":"en_US","og_type":"article","og_title":"Bucket Sort in C# - Code Maze","og_description":"Bucket sort is a sorting algorithm that works by partitioning an array into several buckets. Let's see how to implement Bucket Sort in C#.","og_url":"https:\/\/code-maze.com\/bucket-sort-csharp\/","og_site_name":"Code Maze","article_published_time":"2022-05-31T06:00:59+00:00","article_modified_time":"2022-06-05T11:40:16+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\/bucket-sort-csharp\/#article","isPartOf":{"@id":"https:\/\/code-maze.com\/bucket-sort-csharp\/"},"author":{"name":"Code Maze","@id":"https:\/\/code-maze.com\/#\/schema\/person\/09d29b223012c8e94a68ba62861d0b04"},"headline":"Bucket Sort in C#","datePublished":"2022-05-31T06:00:59+00:00","dateModified":"2022-06-05T11:40:16+00:00","mainEntityOfPage":{"@id":"https:\/\/code-maze.com\/bucket-sort-csharp\/"},"wordCount":1404,"commentCount":0,"publisher":{"@id":"https:\/\/code-maze.com\/#organization"},"image":{"@id":"https:\/\/code-maze.com\/bucket-sort-csharp\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","keywords":["algorithm","bucket sort","sorting","sorting algorithm"],"articleSection":["Algorithm","C#"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/code-maze.com\/bucket-sort-csharp\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/code-maze.com\/bucket-sort-csharp\/","url":"https:\/\/code-maze.com\/bucket-sort-csharp\/","name":"Bucket Sort in C# - Code Maze","isPartOf":{"@id":"https:\/\/code-maze.com\/#website"},"primaryImageOfPage":{"@id":"https:\/\/code-maze.com\/bucket-sort-csharp\/#primaryimage"},"image":{"@id":"https:\/\/code-maze.com\/bucket-sort-csharp\/#primaryimage"},"thumbnailUrl":"https:\/\/code-maze.com\/wp-content\/uploads\/2021\/12\/social-csharp.png","datePublished":"2022-05-31T06:00:59+00:00","dateModified":"2022-06-05T11:40:16+00:00","description":"Bucket sort is a sorting algorithm that works by partitioning an array into several buckets. Let's see how to implement Bucket Sort in C#.","breadcrumb":{"@id":"https:\/\/code-maze.com\/bucket-sort-csharp\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/code-maze.com\/bucket-sort-csharp\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/code-maze.com\/bucket-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\/bucket-sort-csharp\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/code-maze.com\/"},{"@type":"ListItem","position":2,"name":"Bucket 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\/69957","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=69957"}],"version-history":[{"count":5,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/69957\/revisions"}],"predecessor-version":[{"id":70739,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/posts\/69957\/revisions\/70739"}],"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=69957"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/categories?post=69957"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code-maze.com\/wp-json\/wp\/v2\/tags?post=69957"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}