使用 QuickSort 按日历顺序对月份进行排序
Using QuickSort to sort months in calendar order
我正在编写一个需要能够对天气数据进行排序的程序。其中一个功能是,当按月对数据进行排序时,它必须按照日历中出现的顺序对月份进行排序(如果按升序排列,则必须是一月、二月、三月等;而不是四月、八月等).
我遇到的问题是算法 (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 循环只是为了查看数组是否已排序。
将您的月份转换为整数。你想要一个 int[]
.
排序 int[]
.
将 int[]
转换回 string[]
(月份名称)。
用排序后的值覆盖原始 month
数组中的所有值。
我正在编写一个需要能够对天气数据进行排序的程序。其中一个功能是,当按月对数据进行排序时,它必须按照日历中出现的顺序对月份进行排序(如果按升序排列,则必须是一月、二月、三月等;而不是四月、八月等).
我遇到的问题是算法 (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 循环只是为了查看数组是否已排序。
将您的月份转换为整数。你想要一个
int[]
.排序
int[]
.将
int[]
转换回string[]
(月份名称)。用排序后的值覆盖原始
month
数组中的所有值。