diff --git a/sorting/README.md b/sorting/README.md index d9d229ba..d0b820d6 100644 --- a/sorting/README.md +++ b/sorting/README.md @@ -6,6 +6,11 @@ 2. [Insertion Sort](c-or-cpp/insertion-sort.cpp) 3. [Selection Sort](c-or-cpp/selection-sort.cpp) +### C# +1. [Bubble Sort](csharp/bubble-sort.cs) +2. [Insertion Sort](csharp/insertion-sort.cs) +3. [Selection Sort](csharp/selection-sort.cs) + ### Python 1. [Bubble Sort](python/bubble-sort.py) diff --git a/sorting/csharp/bubble-sort.cs b/sorting/csharp/bubble-sort.cs new file mode 100644 index 00000000..7346933c --- /dev/null +++ b/sorting/csharp/bubble-sort.cs @@ -0,0 +1,28 @@ +using System; + +public class Program +{ + public static void Main() + { + int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 }; + Sort(arr); + var result = string.Join(" ", arr); + Console.WriteLine(result); + } + + public static void Sort(int[] source) + { + for (int write = 0; write < source.Length; write++) + { + for (int sort = 0; sort < source.Length - 1; sort++) + { + if (source[sort] > source[sort + 1]) + { + var temp = source[sort + 1]; + source[sort + 1] = source[sort]; + source[sort] = temp; + } + } + } + } +} \ No newline at end of file diff --git a/sorting/csharp/insertion-sort.cs b/sorting/csharp/insertion-sort.cs new file mode 100644 index 00000000..02e4184f --- /dev/null +++ b/sorting/csharp/insertion-sort.cs @@ -0,0 +1,33 @@ +using System; + +public class Program +{ + public static void Main() + { + int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 }; + Sort(arr); + var result = string.Join(" ", arr); + Console.WriteLine(result); + } + + private static void Sort(int[] source) + { + int n = source.Length; + for (int i = 1; i < n; ++i) + { + int key = source[i]; + int j = i - 1; + + // Move elements of arr[0..i-1], + // that are greater than key, + // to one position ahead of + // their current position + while (j >= 0 && source[j] > key) + { + source[j + 1] = source[j]; + j = j - 1; + } + source[j + 1] = key; + } + } +} \ No newline at end of file diff --git a/sorting/csharp/selection-sort.cs b/sorting/csharp/selection-sort.cs new file mode 100644 index 00000000..8a44bac9 --- /dev/null +++ b/sorting/csharp/selection-sort.cs @@ -0,0 +1,37 @@ +using System; + +public class Program +{ + public static void Main() + { + int[] arr = { 800, 11, 50, 771, 649, 770, 240, 9 }; + Sort(arr); + var result = string.Join(" ", arr); + Console.WriteLine(result); + } + + private static void Sort(int[] source) + { + int n = source.Length; + + // One by one move boundary of unsorted subarray + for (int i = 0; i < n - 1; i++) + { + // Find the minimum element in unsorted array + int min_idx = i; + for (int j = i + 1; j < n; j++) + { + if (source[j] < source[min_idx]) + { + min_idx = j; + } + } + + // Swap the found minimum element with the first + // element + int temp = source[min_idx]; + source[min_idx] = source[i]; + source[i] = temp; + } + } +} \ No newline at end of file