【问题标题】:Sort algorithm to sort a list of strings (C#)排序算法对字符串列表进行排序(C#)
【发布时间】:2013-03-17 06:00:22
【问题描述】:

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

【问题讨论】:

  • 首先,将arraytemp 的类型分别更改为string[]string 会发生什么?
  • @Koterpillar 主要问题是您不能使用 www3.picturepush.com/photo/a/12433536/1024/Anonymous/…
  • 因此String.Compare,正如@cHao 的回答。

标签: algorithm list sorting alphabetical


【解决方案1】:

您可能需要逐个字符地比较字符串。

在伪代码中:

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"

【讨论】:

  • 你能写出完整的代码吗?我是一个完整的初学者,所以我并没有真正得到你的伪代码。
  • 作业的部分目的是让你自己编写一些代码。 :) 让我知道需要澄清的部分,我会解释。
猜你喜欢
  • 1970-01-01
  • 2018-08-17
  • 2015-03-26
  • 1970-01-01
  • 1970-01-01
  • 2017-02-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多