-2

The title might not be descriptive but stay with me. This is how buble sorting should look like:

string s = Console.ReadLine();
StringBuilder sb = new StringBuilder(s);
        for (int i = 0; i < sb.Length; i++)
        {
            for (int j = 0; j < sb.Length - 1; j++)
            {
                if (sb[j] > sb[j + 1])
                {
                    char tmp = sb[j];
                    sb[j] = sb[j + 1];
                    sb[j + 1] = tmp;
                }
            }
        }
        s = sb.ToString();
        Console.WriteLine(s);

However I accidentally wrote it like this and I don't know why is this working shouldn't I at least get a indexOutOfRange exception? ->

string s = Console.ReadLine();
            StringBuilder str = new StringBuilder(s);

            for (int i = 0; i < s.Length; i++)
            {
                for (int j = 0; j < str.Length; j++)
                {
                    if (str[i] < str[j])
                    {
                        var tmp = str[j];
                        str[j] = str[i];
                        str[i] = tmp;
                    } 
                }
            }

            s = str.ToString();
            Console.WriteLine(s);

Just to clarify this orders the letters of a word in alphabetical order.

user6879072
  • 441
  • 1
  • 7
  • 17
  • 1
    Your indexes are always in range in the second version. You use only `i` and `j`, and both are always less than `Length`, which is the same for both the string and its copy in the `StringBuilder`. Why would you expect an exception? – Jeroen Mostert Nov 04 '16 at 17:35
  • 2
    Most or all of the arguments of the `Questions seeking debugging help ("why isn't this code working?")` are valid for this "why does this code work" question. So, I'm voting to close. By the way, this is probably the first "why does this code work" question I encounter here on SO :) – fvu Nov 04 '16 at 17:36

1 Answers1

0

In your first approach you went with j from 0 to Length - 1 and kept adding 1 when comparing the characters.

In your second approach you went with j from 0 to Length but did not added 1 when comparing characters.

See these both ways work the same and you get no exception.

meJustAndrew
  • 6,011
  • 8
  • 50
  • 76