After working out Selection Sort, Count Sort and Insertion Sort, I have decided to continue with the last easy sorting method – Bubble Sort in C#.
The other advanced sorting, using recursion can also be found here, but I am not going to present them in my blog, as far as I have used google for some hints for the code.
So, lets start with bubble sort – What does it do? Simply it takes each pair of elements, compares them and swaps them if needed. Trivial and easy as much as Insertion Sort and Selection Sort, but anyhow challenging enough for me in order to recall my C# writing skills.
Pretty much that is all 🙂 Enjoy your day!
And last but not least – here comes the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
using System; using System.Collections.Generic; using System.Linq; class MainClass { public static void Main () { Console.WriteLine ("Welcome to Bubble Sort"); string sInput = Console.ReadLine (); List myList = sInput.Select (c => c.ToString ()).ToList (); for (int i = 0; i < myList.Count-1; i++) { for (int z = myList.Count-2; z > 0; z--) { if (int.Parse(myList[z])<int.parse(mylist[z+1])) {="" swap="" (mylist,="" z,="" z="" +="" 1);="" }="" for="" (int="" i="0;" <="" mylist.count;="" i++)="" console.write(mylist[i]);="" public="" static="" void="" swap(ilist<string=""> list, int indexA, int indexB) { string tmp = list[indexA]; list[indexA] = list[indexB]; list[indexB] = tmp; } } |
Enjoy it! 🙂