.net版 字符串数组桶排序算法
现要将字符串数组按首字母做排序,如:
string[] sortStr = new string[] {"Jack","John","Ja","Bob","Bay","Candy","Enk","Fuk","Amy","Day","Mum","Num","Ju","Fee" };
于是想到了利用桶排序的方法
首先要定义一个数组包含所有的首字母,如:
string[] strArray = new string[] {"A","B","C","D","E","F","G","H","I","J","K","L","M","N" };
因为有重复的首字母存在,所以要定义一个二维数组来存放相同首字母的数组元素,其中行数就是strArray.Length,而列数就是sortStr.Length,如:
string[,] finaArr = new string[strArray.Length, sortStr.Length];
这里还需要一个准备工作,就是取每个元素的首字母,如:
private string GetFirstLetter(string str){
if (string.IsNullOrEmpty(str)) return "";
return str.Substring(0, 1);
}
好了,现在可以开始排序算法了,思路就是将数组sortStr中的每一个元素中的首字母与数组strArray进行比较,然后存入数组finaArr相应的行中,如:
if (string.IsNullOrEmpty(str)) return "";
return str.Substring(0, 1);
}
foreach (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;
}
}
}
做到这里,排序就完成了,只需输出就可以了,如:
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;
}
}
}
StringBuilder 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("<br>");
j++;
}
}
return bui.ToString();
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("<br>");
j++;
}
}
return bui.ToString();
完成了,有什么不对的地方,请大家批评指正,谢谢