How can a bubble sort an array of strings?

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 managed to align the decimal number, but I suck the line, I have a text file with months in it, and I need to sort it in alphabetical order. I get an error message:

operator> cannot be used to enter string and string

Help will be appreciated.

+5
source share
2 answers

You can use string.Compare (x, y) instead of < , which returns 0 if the string is equal, otherwise an integer indicating their relative position in 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 the case during the comparison, you should use string.Compare (letters[index], letters[index + 1], true)

+5
source

You can use String.CompareOrdinal for strings. It would also be better if you invert the if 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 case-sensitive comparisons using sort orders. For more information about words, strings, and ordinal sorts, see System.Globalization.CompareOptions. To perform case insensitive comparisons using ordinal sorting rules, call the Compare (String, String, StringComparison) method with the compareType argument set to StringComparison.OrdinalIgnoreCase.

0
source

Source: https://habr.com/ru/post/1247591/


All Articles