Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to perform Merge Sort using C#?
Merge Sort is a sorting algorithm that uses the divide and conquer method. It divides the array into two halves, recursively sorts each half, and then merges them back together in sorted order. This process continues until the entire array is sorted.
How Merge Sort Works
Merge Sort follows these steps −
-
Divide: Split the array into two halves at the middle point
-
Conquer: Recursively sort both halves
-
Merge: Combine the two sorted halves into a single sorted array
Algorithm
The merge sort algorithm consists of two main functions −
static void mergeSort(int[] arr, int left, int right) {
if (left
Example
using System;
class MergeSortExample {
static public void merge(int[] arr, int p, int q, int r) {
int i, j, k;
int n1 = q - p + 1;
int n2 = r - q;
int[] L = new int[n1];
int[] R = new int[n2];
for (i = 0; i
The output of the above code is −
Merge Sort
Initial array is: 76 89 23 1 55 78 99 12 65 100
Sorted Array is: 1 12 23 55 65 76 78 89 99 100
How It Works
The mergeSort() function calculates the midpoint q and recursively sorts both halves. Then it calls merge() to combine the sorted subarrays −
if (p
The merge() function takes two sorted subarrays and merges them into a single sorted array. It creates temporary arrays L and R, then compares elements from both arrays and places them back in the original array in sorted order.
Time and Space Complexity
| Complexity | Best Case | Average Case | Worst Case |
|---|---|---|---|
| Time Complexity | O(n log n) | O(n log n) | O(n log n) |
| Space Complexity | O(n) | ||
Conclusion
Merge Sort is a stable, divide-and-conquer sorting algorithm with consistent O(n log n) time complexity. It guarantees optimal performance for all input cases, making it suitable for large datasets where predictable performance is required.
