Created
June 21, 2024 00:54
-
-
Save hsynkrcf/cb2542b6eaec9ad06fc97fa33d2a1538 to your computer and use it in GitHub Desktop.
Merge Sort Algorithm Performed On C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public int[] MergeSort(int[] arr, int left, int right) | |
{ | |
if (left < right) | |
{ | |
int mid = (left + right) / 2; | |
MergeSort(arr, left, mid); | |
MergeSort(arr, mid + 1, right); | |
Merge(arr, left, mid, right); | |
} | |
return arr; | |
} | |
private void Merge(int[] arr, int left, int mid, int right) | |
{ | |
int n1 = mid - left + 1; | |
int n2 = right - mid; | |
int[] L = new int[n1]; | |
int[] R = new int[n2]; | |
for (int i = 0; i < n1; ++i) | |
L[i] = arr[left + i]; | |
for (int j = 0; j < n2; ++j) | |
R[j] = arr[mid + 1 + j]; | |
int k = left; | |
int i = 0, j = 0; | |
while (i < n1 && j < n2) | |
{ | |
if (L[i] <= R[j]) | |
{ | |
arr[k] = L[i]; | |
i++; | |
} | |
else | |
{ | |
arr[k] = R[j]; | |
j++; | |
} | |
k++; | |
} | |
while (i < n1) | |
{ | |
arr[k] = L[i]; | |
i++; | |
k++; | |
} | |
while (j < n2) | |
{ | |
arr[k] = R[j]; | |
j++; | |
k++; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment