Implement Merge Sort Using C-Sharp
💻 coding

Implement Merge Sort Using C-Sharp

1 min read 287 words
1 min read
ShareWhatsAppPost on X
  • 1Merge sort is an efficient, comparison-based sorting algorithm that preserves the input order of equal elements.
  • 2It is a divide and conquer algorithm invented by John von Neumann in 1945.
  • 3The time complexity of merge sort is O(n log n), making it suitable for large datasets.

AI-generated summary · May not capture all nuances

Key Insight
AskGif

"Merge sort is an efficient, comparison-based sorting algorithm that preserves the input order of equal elements."

Implement Merge Sort Using C-Sharp

In computer science, merge sort (also commonly spelled mergesort) is an efficient, general-purpose, comparison-based sorting algorithm. Most implementations produce a stable sort, which means that the implementation preserves the input order of equal elements in the sorted output. Merge sort is a divide and conquer algorithm that was invented by John von Neumann in 1945. A detailed description and analysis of bottom-up mergesort appeared in a report by Goldstine and von Neumann as early as 1948.

using System;

namespace MergeSort
{
 class Program
 {
 private static void PrintArray(int[] arr)
 {
 for(int i = 0; i < arr.Length; i++)
 {
 Console.Write(arr[i] + " ");
 }
 Console.WriteLine();
 }

 private static void Merge(int[] arr, int start, int mid, int end)
 {
 int[] temp = new int[arr.Length];
 int i = start;
 int j = mid;
 int k = 0;
 while(i<mid && j < end)
 {
 if (arr[i] < arr[j])
 {
 temp[k] = arr[i];
 i++;
 k++;
 }
 else
 {
 temp[k] = arr[j];
 j++;
 k++;
 }
 }

 while (i < mid)
 {
 temp[k] = arr[i];
 k++;
 i++;
 }

 while( j < end)
 {
 temp[k] = arr[j];
 k++;
 j++;
 }

 for(int x = start, y=0; x < end; x++,y++)
 {
 arr[x] = temp[y];
 }
 }

 private static void MergeSortUtil(int[] arr, int start, int end)
 {
 if (end > start)
 {
 int mid = (start + end) / 2;
 MergeSortUtil(arr, start, mid);
 MergeSortUtil(arr, mid + 1, end);
 Merge(arr, start, mid, end);
 }
 }

 private static void MergeSort(int[] arr)
 {
 MergeSortUtil(arr, 0, arr.Length);
 }

 static void Main(string[] args)
 {
 int[] arr = new int[]{ 4, 7, 2, 8, 1, 9, 3, 5, 6 };
 PrintArray(arr);
 MergeSort(arr);
 PrintArray(arr);
 }
 }
}

This is using divide and conquer approach and Time Complexity of the above solution is O(nlogn).

Enjoyed this article?

Share it with someone who'd find it useful.

ShareWhatsAppPost on X

AskGif

Published on 19 July 2018 · 1 min read · 287 words

Part of AskGif Blog · coding

You might also like

Implement Merge Sort Using C-Sharp | AskGif Blog