我正在编写一个程序,它需要能够对天气数据进行排序。其中一个功能是在按月份排序数据时,必须按照它们在日历中出现的顺序排序(如果按升序排序,则必须是一月,二月,三月等,而不是四月,八月等)。
我的问题是算法(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循环只是为了检查数组是否已经正确排序。