排序算法对字符串列表进行排序(C#)

时间:2013-03-17 06:00:23

标签: algorithm list sorting alphabetical

我正在为uni执行此任务,并且要求是我使用任何排序算法按字母顺序对List进行排序(不区分大小写)。基本上说如果列表包含一些字符串,例如“a”“C”“b”“1”和“3”它将它分类为“1”“3”“a”“b”“C”或“ a“”b“”C“”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;
                    }
                }
            }
        }

1 个答案:

答案 0 :(得分:1)

你可能需要比较字符串char by char。

在伪代码中:

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"