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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With