[英]C# Sort 3 arrays with Bubble sort
我有排序“ arr1”的氣泡排序算法。
static int yearAscDes(int value)`
{
if (value == 0)
{
int[] arr1 = { 1930, 1931, 2016, 2014, 2012 };
int temp1 = 0;
for (int i1 = 0; i1 < arr1.Length; i1++)
{
for (int j1 = 0; j1 < arr1.Length - 1; j1++)
{
if (arr1[j1] < arr1[j1 + 1])
{
temp1 = arr1[j1 + 1];
arr1[j1 + 1] = arr1[j1];
arr1[j1] = temp1;
}
}
}
for (int i1 = 0; i1 < arr1.Length; i1++)
{
Console.Write(arr1[i1] + " \n");
}
return 0;
}
我想使用此算法對3個不同的數組進行排序,它們相互比較。
例如
int[] arr1 = {1930, 1931, 2016, 2014, 2012};
string[] Months = {"Jan", "March", "Dec", "May", "Sept"};
int[] Num = {10, 5, 1, 3, 12};
如果我有這些數組,並按升序對arr1排序,則希望結果看起來像這樣:
結果:
arr1個月數
2016年12月1日
2014年5月3日
2012年9月12日
1931年3月5日
1930年1月10日
如果可以解決,則應僅使用1個DateTime
數組
DateTime[] dt = {new DateTime(1930, 1, 10), new DateTime(1931, 3, 5) /*...*/};
如果由於某種原因您由於某種原因而不能這樣做,那么下一個最好的事情就是制作一個自己的班級,該班級有一年,一個月和一天,並包括一個為您做比較的方法。
如果您有興趣將此功能用於您的工作或副項目,建議您使用DateTime
。 它可以容納您關心的所有事物以及更多。 您也可以在數組中Sort()
或.orderBy(..)
。
但是,如果您對自己的事情的實際實現感興趣,那么為了進行練習,我們必須有兩個假設。
因此,您應該使用2d數組或KeyValue對數組。 一個將是您的Year,另一個將保留一個初始索引。
然后,完成對Years數組的排序后,您可以查看Years值的初始索引,並從Months數組和Days數組中獲取該索引的元素。
另一個想法:您可以保持3個數組不變,但是當您swap
Years數組的索引時,請交換其他兩個數組。 只要確保僅對Years陣列中的游泳使用檢查條件即可。 這樣,對Years數組進行排序時,您還將根據Years數組索引對其他兩個數組進行排序。 您的代碼:
if (arr1[j1] < arr1[j1 + 1])
{
temp1 = arr1[j1 + 1];
arr1[j1 + 1] = arr1[j1];
arr1[j1] = temp1;
}
應該像這樣
if (arr1[j1] < arr1[j1 + 1])
{
temp1 = arr1[j1 + 1];
arr1[j1 + 1] = arr1[j1];
arr1[j1] = temp1;
tempMonths = months[j1 + 1];
months[j1 + 1] = months[j1];
months[j1] = tempMonths;
tempDays = days[j1 + 1];
days[j1 + 1] = days[j1];
days[j1] = tempDays;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.