-
Notifications
You must be signed in to change notification settings - Fork 32
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #55 from NikeshGangwar41/main
Added Merge Sort algorithm in C++
- Loading branch information
Showing
1 changed file
with
83 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,83 @@ | ||
#include <iostream> | ||
|
||
void merge(int arr[], int l, int m, int r) { | ||
int n1 = m - l + 1; | ||
int n2 = r - m; | ||
|
||
// Create temporary arrays | ||
int left[n1]; | ||
int right[n2]; | ||
|
||
// Copy data to temporary arrays left[] and right[] | ||
for (int i = 0; i < n1; i++) { | ||
left[i] = arr[l + i]; | ||
} | ||
for (int j = 0; j < n2; j++) { | ||
right[j] = arr[m + 1 + j]; | ||
} | ||
|
||
// Merge the temporary arrays back into arr[l..r] | ||
int i = 0; // Initial index of first subarray | ||
int j = 0; // Initial index of second subarray | ||
int k = l; // Initial index of merged subarray | ||
|
||
while (i < n1 && j < n2) { | ||
if (left[i] <= right[j]) { | ||
arr[k] = left[i]; | ||
i++; | ||
} else { | ||
arr[k] = right[j]; | ||
j++; | ||
} | ||
k++; | ||
} | ||
|
||
// Copy the remaining elements of left[], if any | ||
while (i < n1) { | ||
arr[k] = left[i]; | ||
i++; | ||
k++; | ||
} | ||
|
||
// Copy the remaining elements of right[], if any | ||
while (j < n2) { | ||
arr[k] = right[j]; | ||
j++; | ||
k++; | ||
} | ||
} | ||
|
||
void mergeSort(int arr[], int l, int r) { | ||
if (l < r) { | ||
int m = l + (r - l) / 2; | ||
|
||
// Sort first and second halves | ||
mergeSort(arr, l, m); | ||
mergeSort(arr, m + 1, r); | ||
|
||
// Merge the sorted halves | ||
merge(arr, l, m, r); | ||
} | ||
} | ||
|
||
int main() { | ||
int arr[] = {12, 11, 13, 5, 6, 7}; | ||
int arr_size = sizeof(arr) / sizeof(arr[0]); | ||
|
||
std::cout << "Original array: "; | ||
for (int i = 0; i < arr_size; i++) { | ||
std::cout << arr[i] << " "; | ||
} | ||
std::cout << std::endl; | ||
|
||
// Perform merge sort | ||
mergeSort(arr, 0, arr_size - 1); | ||
|
||
std::cout << "Sorted array: "; | ||
for (int i = 0; i < arr_size; i++) { | ||
std::cout << arr[i] << " "; | ||
} | ||
std::cout << std::endl; | ||
|
||
return 0; | ||
} |