2016-04-21 72 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.