2014/06/15

Sorting a string to alphabetical order using Bubble sort algorithm and Lambda


Programming Language used: C#.net

In this article, we will learn how to manipulate further our string value using sorting algorithms(In my case, I've used bubble sort) and LINQ to simplify the process.

So, to start with, let me list again the prerequisites before you delve into the topic:

• Familiarization with C#.net or VB.net
• Used Visual Studio
• Basic idea on algorithms

Alright, so here we go. I'll guide you.

Step 1: Create a console application. Name it stringSort

Step 2: Create a static string constructor StartSort(string name) and put a sorting algorithm with the method.

**notes: Make use of generics like List<T>() to accomplish the task in converting string to character.

Your code should look like this:
  /// <summary>
        /// using Bubble Sort
        /// </summary>
        public static string StartSort(string name)
        {
            var tempLetter = "";
            string arrangedName = "";
            List<string> ListLetters = new List<string>(); //we use the advantage of generics for a mutable version of array.
            arrangedName = "";
            for (int i = 0; i < name.Length; i++)
            {
                ListLetters.Add(name.Substring(i, 1)); //limit the string to 1 so that its convertible to character.
            }
            for (int i = 0; i < name.Length; i++)
            {
                for (int j = i; j < name.Length; j++)
                {
                    if (char.Parse(ListLetters[i]) > char.Parse(ListLetters[j]))
                    {
                        tempLetter = ListLetters[i];
                        ListLetters[i] = ListLetters[j];
                        ListLetters[j] = tempLetter;
                    }
                }
            }
            foreach (var listLetter in ListLetters)
            {
                arrangedName += listLetter;
            }
            return arrangedName;
        }


This seems a little lengthy at first glance. Since we're using bubble sort algorithm, we need nested for-loop to accomplish the task. The reason for this is for the individual arrays to be evaluated then do a swapping if the ASCII equivalent of that letter is greater than its adjacent letters. And, bubble sort behaves that way. Don't ask for more explanation, do some google.

Also, its not really required to use generics if you don't want to. You can use the old-conventional way of storing each individual into an array.

Like this:

char[] myname = new char[] { 's', 'o', 'n', 'n', 'y' }; //old way of doing arrays. Immutable.

Honestly speaking this is just based on your personal preference. If you're used in an old way of using arrays then go. But I tell you this. Generics are more more flexible than you might think since it solves some OR most of the complex coding structure. Also, you can convert them into an array if you like.

So I encourage you to use this instead:

List<char> mychar = new List<char>(); //mutable arrays/collections

Whenever you're getting an input from the user, this is very useful.


Anyway, this consumed 16 lines of code.

Now how about we use Lambda to accomplish the same task?
This will blow your mind out.

Alternative: Use lambda to sort string of characters.

Paste this code into the main method and display this using Console.Writeline():

string.Concat("sonny".OrderBy(n => n))

Now, what happened? This one-liner code for the win does the same thing as using sorting algorithms which consumed 16 lines of code. This can save you time and can mean lesser bugs in the code as it grows.

Bottom line: In the end, it is up to your personal preference or what your development team prefers to use in the middle of development in meeting some standards of proper coding the System or an Application to avoid Spaghetti codes. But for the sake of sharpening your skills in solving complex problems, I prefer you to create your own algorithm to exercise your problem-solving skills.

No comments: