Search code examples
c#bubble-sort

Bubble sort letters


I could use some help with this code, it is almost done. I just need to convert it back to letters, but I can't get it to work. Does anyone know how it should be done?

namespace Sorteringen
{
    class Program
    {
        static void Main(string[] args)
        {
            {
                int[] letters = { 'c', 's', 'a', 'k', 'x', 'l', 'j' };
                int t;

                for (int j = 0; j <= letters.Length - 2; j++)
                {
                    for (int i = 0; i <= letters.Length - 2; i++)
                    {
                        if (letters[i] > letters[i + 1])
                        {
                            t = letters[i + 1];
                            letters[i + 1] = letters[i];
                            letters[i] = t;
                        }
                    }                   
                }               
               foreach (int aray in letters)
               Console.WriteLine(aray +  " " );
               Console.ReadLine();
            }

        }
    }
}

Solution

  • You just need to declare aray as a char instead of an int. I'd recommend a clearer variable name as well:

    foreach (char ch in letters)
        Console.Write(ch +  " " );
    

    Also, why not just declare letters as a char[] and t as a char?

    char[] letters = { 'c', 's', 'a', 'k', 'x', 'l', 'j' };
    char t;
    
    for (int j = 0; j <= letters.Length - 2; j++)
    {
        for (int i = 0; i <= letters.Length - 2; i++)
        {
            if (letters[i] > letters[i + 1])
            {
                t = letters[i + 1];
                letters[i + 1] = letters[i];
                letters[i] = t;
            }
        }                   
    }
    

    Then you can just use string.Join to output the result:

    Console.WriteLine(string.Join(" ", letters));