|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Text; |
| 5 | +using System.Threading.Tasks; |
| 6 | + |
| 7 | +namespace Sorting_Algorithms_In_C_Sharp |
| 8 | +{ |
| 9 | + public static class BucketSort |
| 10 | + { |
| 11 | + //Bucket sort breaks a list down into sub-lists, you can then use another algo to sort the sub-lists |
| 12 | + //Bucketsort isn't a good choice if you don't know the range or distribution of the data |
| 13 | + //Bucket Sort time complexity |
| 14 | + //Average case: O(n+k) - k being the number of buckets that were created |
| 15 | + //Worst case: O(N^2) |
| 16 | + |
| 17 | + //In this case, we will focus on building an algorithm that uses bucketsort to sort an array of integers between 1 and 99 |
| 18 | + //we will also assume that the integers in the passed array are evenly distributed |
| 19 | + public static List<int> BucketSort1(params int[] x) |
| 20 | + { |
| 21 | + List<int> result = new List<int>(); |
| 22 | + |
| 23 | + //Determine how many buckets you want to create, in this case, the 10 buckets will each contain a range of 10 |
| 24 | + //1-10, 11-20, 21-30, etc. since the passed array is between 1 and 99 |
| 25 | + int numOfBuckets = 10; |
| 26 | + |
| 27 | + //Create buckets |
| 28 | + List<int>[] buckets = new List<int>[numOfBuckets]; |
| 29 | + for (int i = 0; i < numOfBuckets; i++) |
| 30 | + buckets[i] = new List<int>(); |
| 31 | + |
| 32 | + //Iterate through the passed array and add each integer to the appropriate bucket |
| 33 | + for (int i = 0; i < x.Length; i++) |
| 34 | + { |
| 35 | + int buckitChoice = (x[i] / numOfBuckets); |
| 36 | + buckets[buckitChoice].Add(x[i]); |
| 37 | + } |
| 38 | + |
| 39 | + //Sort each bucket and add it to the result List |
| 40 | + //Each sublist is sorted using Bubblesort, but you could substitute any sorting algo you would like |
| 41 | + for (int i = 0; i < numOfBuckets; i++) |
| 42 | + { |
| 43 | + int [] temp = BubbleSortList(buckets[i]); |
| 44 | + result.AddRange(temp); |
| 45 | + } |
| 46 | + return result; |
| 47 | + } |
| 48 | + |
| 49 | + //Bubblesort w/ ListInput |
| 50 | + public static int[] BubbleSortList(List<int> input) |
| 51 | + { |
| 52 | + for (int i = 0; i < input.Count; i++) |
| 53 | + { |
| 54 | + for (int j = 0; j < input.Count; j++) |
| 55 | + { |
| 56 | + if (input[i] < input[j]) |
| 57 | + { |
| 58 | + int temp = input[i]; |
| 59 | + input[i] = input[j]; |
| 60 | + input[j] = temp; |
| 61 | + } |
| 62 | + } |
| 63 | + } |
| 64 | + return input.ToArray(); |
| 65 | + } |
| 66 | + ////Call in Program.cs to test |
| 67 | + //int[] x = new int[] { 99, 95, 90, 85, 80, 75, 70, 65, 60, 55, 50, 45, 40, 35, 30, 25, 20, 15, 10, 5, 1 }; |
| 68 | + //List<int> sorted = Bucket_Sort.BucketSort(x); |
| 69 | + //foreach (int i in sorted) |
| 70 | + // Console.WriteLine(i); |
| 71 | + } |
| 72 | +} |
0 commit comments