5
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
  • 1
    FYI: == true is unnecessary since it is just evaluating whether your boolean value equals another boolean value to return a boolean value, since you already have a boolean value to start with you can just use that (while(swap)) Commented Apr 21, 2016 at 9:03

2 Answers 2

5

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)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much!
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.