2016-04-21 118 views
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); 
} 

我已经设法对小数点进行冒泡排序,但是我用字符串来吮吸,我有一个带有月份的文本文件,我需要按字母顺序排序。我得到的错误:如何对字符串数组进行冒泡排序?

operator > cannot be applied to type string and string

帮助,将不胜感激。

+1

FYI:'==真'是不必要的,因为它仅仅是评估您的布尔值是否等于另一个布尔值返回一个布尔值,因为你已经有一个布尔值开始,你可以使用('while(swap)') – Sayse

回答

5

可以使用string.Compare(x,y)代替<,如果字符串相等,返回0,否则一个整数,指示在排序顺序

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

如果你想在比较过程中忽略的情况下它们的相对位置,您应该使用string.Compare (letters[index], letters[index + 1], true)

+0

非常感谢你! – georgeThornton96

0

您可以使用String.CompareOrdinal作为字符串。此外,如果您反转if语句以减少嵌套,会更好。就像这样:

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

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.