Bubble sort string array c#

安稳与你 提交于 2019-12-13 09:42:49

问题


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

回答1:


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



回答2:


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



来源:https://stackoverflow.com/questions/38624840/bubble-sort-string-array-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!