Skip to content

Commit

Permalink
Merge pull request #55 from NikeshGangwar41/main
Browse files Browse the repository at this point in the history
Added Merge Sort algorithm in C++
  • Loading branch information
lilmistake authored Oct 21, 2023
2 parents fdd1f55 + 371c61a commit e734e28
Showing 1 changed file with 83 additions and 0 deletions.
83 changes: 83 additions & 0 deletions DSA_Codesheet/Cpp/MergeSort.cpp
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;
}

0 comments on commit e734e28

Please sign in to comment.