Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to bubble sort a string array?

Tags:

string

c#

sorting

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.

like image 749
georgeThornton96 Avatar asked Apr 21 '16 08:04

georgeThornton96


1 Answers

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)

like image 106
Valentin Avatar answered Nov 16 '22 10:11

Valentin