Bubble sort string array c#

2019-09-21 20:31发布

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);
}

2条回答
闹够了就滚
2楼-- · 2019-09-21 21:02
public void BubbleSortArrayString(string[] letters) //change here
{
bool swap;
string temp; //change this too

do
{
    swap = false;

    for (int index = 0; index < (letters.Length - 1); index++)
    {
        if (letters[index] > letters[index + 1]) //if first number is greater then second then swap
        {
            //swap

            temp = letters[index];
            letters[index] = letters[index + 1];
            letters[index + 1] = temp;
            swap = true;
        }
    }

} while (swap == true);

}

used this code... forgot some answered last time i tried this

查看更多
Fickle 薄情
3楼-- · 2019-09-21 21:16

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;
    }
  }
查看更多
登录 后发表回答