使用QuickSort按日历顺序对月份进行排序

时间:2016-04-12 15:44:37

标签: c# algorithm quicksort

我正在编写一个需要能够对天气数据进行分类的程序。其中一个功能是,按月对数据进行排序时,它必须按日历顺序排序几个月(如果它按升序排列,则必须是1月,2月,3月等等;而不是4月,八月等)。

我遇到的问题是算法(QuickSort)没有按照我想要的方式对数组进行排序。

public static void sortMonths(string[] month,int left,int right)
{
    Dictionary<string,int> monthsDictionary = new Dictionary<string,int>()
    {
        {"January",1},
        {"February",2},
        {"March",3},
        {"April",4},
        {"May", 5},
        {"June", 6},
        {"July", 7},
        {"August", 8},
        {"September", 9},
        {"October", 10},
        {"November", 11},
        {"December", 12},
    };

    int i = left,j = right;

    string[] sortedMonth = month;

    string tempMonth;

    string pivot = sortedMonth[(i+j)/2];

    while(i<=j)
    {
        while(monthsDictionary[sortedMonth[i]] < monthsDictionary[pivot])
            i++;
        while(monthsDictionary[sortedMonth[j]] > monthsDictionary[pivot])
            j--;
        if(i <= j)
        {
            tempMonth = sortedMonth[i];
            sortedMonth[i] = sortedMonth[j];
            sortedMonth[j] = tempMonth;

            i++;
            j--;
        }
    };

    if(left < j)
    {
        sortMonths(sortedMonth,left,j);
    }
    else if(i < right)
    {
        sortMonths(sortedMonth,i,right);
    }

    for(int ctr = 0;ctr < sortedMonth.Length; ctr++)
        Console.WriteLine(sortedMonth[ctr]);
}

我听说接近这个任务的一种方法就是使用字典将月份名称指向相应的数字值,这就是我正在做的事情,但它似乎仍然无法工作。我只是想知道我做错了什么,我该怎么做才能解决这个问题。也许这个任务有更好的解决方案,或者我可以使用更好的算法?此外,我不允许使用预定义的排序函数,最后的for循环只是为了查看数组是否正常排序。

1 个答案:

答案 0 :(得分:1)

  1. 将您的月份转换为整数。您需要int[]

  2. int[]

  3. 进行排序
  4. int[]转换回string[](月份名称)。

  5. 使用已排序的数据覆盖原始month数组中的所有值。

相关问题