Here is the code:
public int[] MergeSort(int[] arr)
{
if (arr.Length == 1)
{
return arr;
}
int i = arr.Length / 2;
int[] a1 = new int[i];
for (int j = 0; j < i; j++)
{
a1[j] = arr[j];
}
int[] a2 = new int[arr.Length - i];
int h = 0;
for (int k = i; k < arr.Length; k++)
{
a2[h] = arr[k];
h++;
}
a1 = MergeSort(a1);
a2 = MergeSort(a2);
return Merge(a1, a2);
}
public int[] Merge(int[] nums1, int[] nums2)
{
int i = 0;
int j = 0;
int k = 0;
int m = nums1.Length;
int n = nums2.Length;
int[] temp = new int[m + n];
while (i < m && j < n)
{
if (nums1[i] < nums2[j])
{
temp[k] = nums1[i];
i++;
}
else
{
temp[k] = nums2[j];
j++;
}
k++;
}
while (i == m && j < n)
{
temp[k] = nums2[j];
j++;
k++;
}
while (j == n && i < m)
{
temp[k] = nums1[i];
i++;
k++;
}
return temp;
}
Popular Posts
-
Here is the code: // => Brute Force Solution: O(m* n) static long arrayManipulation(int n, int[][] queries) { ...
-
Whatever it is one fine day everyone on this planet who are born have to die for sure. When you are close ones are with you, you wont know ...
-
HTML: <div class="outer-container"> <div class="inner-container"> <div class="t...
2 comments:
Post a Comment