.net版 字串陣列桶排序演算法

iDotNetSpace發表於2009-02-06

現要將字串陣列按首字母做排序,如:

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gtstring[] sortStr = new string[] {"Jack","John","Ja","Bob","Bay","Candy","Enk","Fuk","Amy","Day","Mum","Num","Ju","Fee" };

於是想到了利用桶排序的方法
首先要定義一個陣列包含所有的首字母,如:

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gtstring[] strArray = new string[] {"A","B","C","D","E","F","G","H","I","J","K","L","M","N" };


因為有重複的首字母存在,所以要定義一個二維陣列來存放相同首字母的陣列元素,其中行數就是strArray.Length,而列數就是sortStr.Length,如:

<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gtstring[,] finaArr = new string[strArray.Length, sortStr.Length];
這裡還需要一個準備工作,就是取每個元素的首字母,如:
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gtprivate string GetFirstLetter(string str){

        
if (string.IsNullOrEmpty(str)) return "";
        
return str.Substring(01);
}
好了,現在可以開始排序演算法了,思路就是將陣列sortStr中的每一個元素中的首字母與陣列strArray進行比較,然後存入陣列finaArr相應的行中,如:
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gtforeach (string s in sortStr) {

            InputElement(s, strArray, finaArr);
}

private void InputElement(string sortStrElement, string[] strArray, string[,] finaArr) {

        
string temp = GetFirstLetter(sortStrElement);
        
for (int i = 0; i < strArray.Length; i++) {

            
if (temp == strArray[i]) {

                
if (string.IsNullOrEmpty(finaArr[i, 0]))
                    finaArr[i, 
0= sortStrElement;
                
else {

                    
int j = 0;
                    
while (!string.IsNullOrEmpty(finaArr[i, j]))
                        j
++;
                    finaArr[i,j] 
= sortStrElement;
                }
                
break;
            }
        }
    }
做到這裡,排序就完成了,只需輸出就可以了,如:
<!--

Code highlighting produced by Actipro CodeHighlighter (freeware)
http://www.CodeHighlighter.com/

--&gtStringBuilder bui = new StringBuilder();

        
for (int i = 0; i < finaArr.GetLength(0); i++){

            
if (string.IsNullOrEmpty(finaArr[i, 0]))
                
continue;
            
int j = 0;
            
while (!string.IsNullOrEmpty(finaArr[i, j])) {

                bui.Append(finaArr[i, j]).Append(
"
");
                j
++;
            }
        }
        
return bui.ToString();

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/12639172/viewspace-545466/,如需轉載,請註明出處,否則將追究法律責任。

相關文章