Reputation: 39
I have this bubble sort algorithm that sorts "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;
}
I want to sort 3 different arrays using this algorithm which they compare with each other.
for e.g.
int[] arr1 = {1930, 1931, 2016, 2014, 2012};
string[] Months = {"Jan", "March", "Dec", "May", "Sept"};
int[] Num = {10, 5, 1, 3, 12};
If I had these arrays and I sort arr1 in ascending order, I want the result to look like this:
Result:
arr1 Months Num
2016 Dec 1
2014 May 3
2012 Sept 12
1931 March 5
1930 Jan 10
Upvotes: 1
Views: 721
Reputation: 1867
If you are interested to make this useful for your work or side project, I'd suggest to use DateTime
. It will hold all the things you care about and many more. You can also you Sort()
or .orderBy(..)
in arrays.
But if you are interested in actual implementation of your thing, for the sake of an exercise, we must have couple of assumptions.
So, you should use 2d array, or an array of KeyValue pairs. one will be your Year, another will hold an initial index.
Then, once you are done sorting your array of Years, you can look at the initial indexes of values of years, and grab elements of that index form array of Months and array of Days.
Another idea:
You can keep the 3 arrays as is, but when you do a swap
of indexes of Years array, do a swap of the other two arrays. Just make sure that you only use a check condition for the swam from Years array. That way, when Years array is sorted, you will also sort the other two arrays according to Years array indexes.
Your code:
if (arr1[j1] < arr1[j1 + 1])
{
temp1 = arr1[j1 + 1];
arr1[j1 + 1] = arr1[j1];
arr1[j1] = temp1;
}
Should be someting like this
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;
}
Upvotes: 0
Reputation: 31204
If you can get away with it, You should use just 1 array of DateTime
DateTime[] dt = {new DateTime(1930, 1, 10), new DateTime(1931, 3, 5) /*...*/};
If you for some reason can't do that because this is homework, then the next best thing would be to make your own class that has a year, a month, and a day, and include a method that does comparison for you.
Upvotes: 4