Home »
.Net »
C# Programs
C# - Sort an Array Using Merge Sort
Here, we are going to learn how to sort an array using merge sort In C#?
By Nidhi Last updated : March 28, 2023
Here, we will sort an integer array using merge sort.
Merge Sort
Merge Sort is the divide and conquer algorithm, here we divide the array into two half's and then merge two sorted halves. Here we used recursion to sort integer array.
C# program to sort an array using merge sort
The source code to sort an integer array using merge sort is given below. The given program is compiled and executed successfully on Microsoft Visual Studio.
// C# program to sort an array
// using merge sort
using System;
class Test {
static void Merge(int[] arr, int low, int mid, int high) {
int[] tempArr = new int[arr.Length];
int left1 = 0;
int temp = 0;
int total = 0;
int loop = 0;
left1 = (mid - 1);
temp = low;
total = (high - low + 1);
while ((low <= left1) && (mid <= high)) {
if (arr[low] <= arr[mid])
tempArr[temp++] = arr[low++];
else
tempArr[temp++] = arr[mid++];
}
while (low <= left1)
tempArr[temp++] = arr[low++];
while (mid <= high)
tempArr[temp++] = arr[mid++];
for (loop = 0; loop < total; loop++) {
arr[high] = tempArr[high];
high--;
}
}
static void Sort(int[] arr, int low, int high) {
int mid = 0;
if (high > low) {
mid = (high + low) / 2;
Sort(arr, low, mid);
Sort(arr, (mid + 1), high);
Merge(arr, low, (mid + 1), high);
}
}
static void Main(string[] args) {
int[] arr = {32, 18, 27, 65, 12, 41, 22, 26, 44};
int length = 0;
int loop = 0;
length = arr.Length;
Sort(arr, 0, length - 1);
Console.WriteLine("Sorted Array:");
for (loop = 0; loop < arr.Length; loop++)
Console.Write(arr[loop] + " ");
Console.WriteLine();
}
}
Output
Sorted Array:
12 18 22 26 27 32 41 44 65
Press any key to continue . . .
Explanation
In the above program, we created a class Sort that contains three static methods Sort(), Merge(), and Main().
Here, we use Sort() method uses divide and conjure technique to sort the given integer array, here we used recursion, to divide and merge arrays partitions.
The Sort class also contains the Main() method, here we create an integer array and then called Sort() method that will sort the array in the ascending order and printed the sorted array on the console screen.
C# Data Structure Programs »