Skip to content

Commit

Permalink
Merge pull request #85 from IRFANSARI/main
Browse files Browse the repository at this point in the history
Added Merge Sort algorithm in CPP under CPP/Sorting-Algorithm folder
  • Loading branch information
YuweAEC authored Oct 18, 2024
2 parents aaf0d3c + fd609f8 commit 5e89a53
Showing 1 changed file with 75 additions and 0 deletions.
75 changes: 75 additions & 0 deletions CPP/SORTING_ALGORITHMS/MergeSort.cpp
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;
}

0 comments on commit 5e89a53

Please sign in to comment.