Feedback

C# - SortByName() BubbleSort String Array

Veröffentlicht von am 11.11.2015
(0 Bewertungen)
SortByName() is a BubbleSort Algorithm to sort the StringArray content alphabetically.
It uses the String Method CompareTo(). This method compares the ASCII numbers and
returns 1 if the name is "higher" and swaps it with the compared name, 0 if it´s equal
and -1 if it´s lower, which means sorted in this case.
It is implemented as a class method for class-intern string arrays.
Here is some sampledata for your Program Main() to see how this is working:

Snippet snip = new Snippet();
snip.StringArray = new string[5];
snip.StringArray[0] = "A";
snip.StringArray[1] = "C";
snip.StringArray[2] = "Z";
snip.StringArray[3] = "I";
snip.StringArray[4] = "B";

snip.ShowAll();

snip.SortByName();

snip.ShowAll();
Console.ReadKey();


class Snippet
    {
        // Your class string Array. You need it to get this running.
        public string[] StringArray {get; set;}

        
        // SortByName() is a BubbleSort Algorithm to sort the Person names alphabetically.
        // It uses String Method CompareTo(). This method compares the ASCII numbers and 
        // returns 1 if the name is "higher" and swaps it with the compared name, 0 if it´s equal 
        // and -1 if it´s lower, which means sorted in this case.
        //
        public void SortByName()
        {
            string[] help = new string[1];

            for (int i = 0; i < StringArray.Length - 1; i++)
            {
                for (int j = i + 1; j < StringArray.Length; j++)
                {
                    if (StringArray[i].CompareTo(StringArray[j]) > 0)
                    {
                        help[0] = StringArray[i];
                        StringArray[i] = StringArray[j];
                        StringArray[j] = help[0];
                    }
                }
            }
        }

        // This Method is just there to show the results on the Console Display
        public void ShowAll()
        {
            foreach (string element in StringArray)
            {
                Console.Write(element.ToString() + " ");
            }
            Console.WriteLine();
        }
    
    }
Abgelegt unter Sorting, Bubblesort, stringArray, sort.

Kommentare zum Snippet

 

Logge dich ein, um hier zu kommentieren!