-
Notifications
You must be signed in to change notification settings - Fork 41
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 #85 from IRFANSARI/main
Added Merge Sort algorithm in CPP under CPP/Sorting-Algorithm folder
- Loading branch information
Showing
1 changed file
with
75 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,75 @@ | ||
#include <iostream> | ||
using namespace std; | ||
|
||
void merge(int arr[], int left, int mid, int right) { | ||
int n1 = mid - left + 1; | ||
int n2 = right - mid; | ||
|
||
// Temporary arrays | ||
int leftArray[n1], rightArray[n2]; | ||
|
||
// Copy data to temporary arrays | ||
for (int i = 0; i < n1; i++) | ||
leftArray[i] = arr[left + i]; | ||
for (int j = 0; j < n2; j++) | ||
rightArray[j] = arr[mid + 1 + j]; | ||
|
||
// Merge the temporary arrays back into arr[left..right] | ||
int i = 0, j = 0, k = left; | ||
while (i < n1 && j < n2) { | ||
if (leftArray[i] <= rightArray[j]) { | ||
arr[k] = leftArray[i]; | ||
i++; | ||
} else { | ||
arr[k] = rightArray[j]; | ||
j++; | ||
} | ||
k++; | ||
} | ||
|
||
// Copy the remaining elements of leftArray[], if any | ||
while (i < n1) { | ||
arr[k] = leftArray[i]; | ||
i++; | ||
k++; | ||
} | ||
|
||
// Copy the remaining elements of rightArray[], if any | ||
while (j < n2) { | ||
arr[k] = rightArray[j]; | ||
j++; | ||
k++; | ||
} | ||
} | ||
|
||
void mergeSort(int arr[], int left, int right) { | ||
if (left < right) { | ||
int mid = left + (right - left) / 2; | ||
|
||
// Sort first and second halves | ||
mergeSort(arr, left, mid); | ||
mergeSort(arr, mid + 1, right); | ||
|
||
// Merge the sorted halves | ||
merge(arr, left, mid, right); | ||
} | ||
} | ||
|
||
int main() { | ||
int arr[] = {12, 11, 13, 5, 6, 7}; | ||
int arrSize = sizeof(arr) / sizeof(arr[0]); | ||
|
||
cout << "Original array:\n"; | ||
for (int i = 0; i < arrSize; i++) | ||
cout << arr[i] << " "; | ||
cout << endl; | ||
|
||
mergeSort(arr, 0, arrSize - 1); | ||
|
||
cout << "Sorted array:\n"; | ||
for (int i = 0; i < arrSize; i++) | ||
cout << arr[i] << " "; | ||
cout << endl; | ||
|
||
return 0; | ||
} |