Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
423 views
in Technique[技术] by (71.8m points)

Bubble sort string array c#

I have this project where I have to sort some txt files, most of them are numbers but one of them is a collection of months. I have the code that sorts the others but not the file containing the months. So i need this code to be changed so I can sort a string array any advice would be brilliant thank you!

public void SortArray(decimal[] numbers)
{
    bool swap;
    decimal temp;

    do
    {
        swap = false;

        for(int index = 0; index < (numbers.Length - 1); index ++)
        {
            if ( numbers[index] > numbers[index+1])
            {
                //swap
                temp = numbers[index];
                numbers[index] = numbers[index + 1];
                numbers[index + 1] = temp;
                swap = true;

            }

        }


    } while (swap == true);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you have an string array like this:

string[] s = {"bbb", "ccc", "aaa"};

The shorter way to sort it, using:

Array.Sort(s);

and the long way to sort it, using:

  for (var i = 1; i < s.Length; i++)
  {
    for (var j = 0; j < s.Length - i; j++)
    {
      if (string.Compare(s[j], s[j + 1], StringComparison.Ordinal) <= 0) continue;
      var temp = s[j];
      s[j] = s[j + 1];
      s[j + 1] = temp;
    }
  }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...