How to bubble sort a string array?

做~自己de王妃 提交于 2021-02-05 04:54:24

问题


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

I have managed to bubble sort a decimal but I'm suck with a string, I have a text file with months in it and I need to sort it in alphabetical order. I get the error:

operator > cannot be applied to type string and string

Help would be appreciated.


回答1:


You can use string.Compare(x,y) instead of <, which returns 0 if the string are equal, otherwise an integer that indicates their relative position in the sort order

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

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

If you want to ignore case during the comparison, you should use string.Compare (letters[index], letters[index + 1], true)




回答2:


You could use String.CompareOrdinal for strings. Also it would be better if you invert your if statement to reduce nesting. Like this:

if (String.CompareOrdinal(letters[index], letters[index + 1]) >= 0) continue;                    
temp = letters[index];
letters[index] = letters[index + 1];
letters[index + 1] = temp;
swap = true;

From MSDN:

This method performs a case-sensitive comparison using ordinal sort rules. For more information about word, string, and ordinal sorts, see System.Globalization.CompareOptions. To perform a case-insensitive comparison using ordinal sort rules, call the Compare(String, String, StringComparison) method with the comparisonType argument set to StringComparison.OrdinalIgnoreCase.



来源:https://stackoverflow.com/questions/36764347/how-to-bubble-sort-a-string-array

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