我为uni做这个赋值,要求是我使用任何排序算法按字母顺序(不区分大小写)对List排序。比如说,如果列表包含一些字符串例如,"a" "C" "b" "1"one_answers"3"它会将其排序为"1" "3" "a" "b" "C" "a" "b" "1" "3"我知道如何排序整数数组(代码下面使用交换排序),但我如何使用字符串列表代替?如何修改下面的代码来对字符串列表按字母顺序排序,同时仍然保持交换排序的原则(在这种情况下)?
注意:我不允许使用List<string>.Sort()
或其他一些简单的代码。
// sort a vector of type int using exchange sort
public void ExchangeSort(int[] array)
{
int pass, i, n = array.Length;
int temp;
// make n-1 passes through the data
for (pass = 0; pass < n - 1; pass++)
{
// locate least of array[pass] ... array[n - 1]
// at array[pass]
for (i = pass + 1; i < n; i++)
{
if (array[i] < array[pass])
{
temp = array[pass];
array[pass] = array[i];
array[i] = temp;
}
}
}
}
您可能需要逐个比较字符串。
在伪代码:for each I from 0 to (shorter string's length - 1):
if left[I] is a letter and right[I] isn't (or vice versa):
the string that has a letter at [I] is "less"
done
else:
("true" here means ignore case)
(you could also say `StringComparison.InvariantCultureIgnoreCase`, but eh)
result = String.Compare(left, I, right[I], I, 1, true)
if result < 0
left is "less"
else if result > 0
right is "less"
else
(both strings are equal so far)
next I
(if you're here, the strings are "equal" up to this point)
if both strings have the same length:
they're equal
else:
the longer string is "greater"