Skip to content

Commit

Permalink
Create Merge Sort
Browse files Browse the repository at this point in the history
Merge Sort
issue laviii123#404
  • Loading branch information
Utkarsh750 authored Oct 25, 2023
1 parent 0598911 commit ba5531b
Showing 1 changed file with 88 additions and 0 deletions.
88 changes: 88 additions & 0 deletions Merge Sort
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
#include <iostream>
#include <vector>

using namespace std;

void merge(vector<int>& arr, int l, int m, int r) {
int n1 = m - l + 1;
int n2 = r - m;

// Create temporary arrays
vector<int> L(n1);
vector<int> R(n2);

// Copy data to temporary arrays L[] and R[]
for (int i = 0; i < n1; i++) {
L[i] = arr[l + i];
}
for (int i = 0; i < n2; i++) {
R[i] = arr[m + 1 + i];
}

// Merge the temporary arrays back into arr[l..r]
int i = 0;
int j = 0;
int k = l;

while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}

// Copy the remaining elements of L[], if there are any
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}

// Copy the remaining elements of R[], if there are any
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}


void mergeSort(vector<int>& arr, int l, int r) {
if (l < r) {

int m = l + (r - l) / 2;


mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);


merge(arr, l, m, r);
}
}

int main() {
vector<int> arr = {12, 11, 13, 5, 6, 7};

cout << "Original array: ";
for (int num : arr) {
cout << num << " ";
}
cout << endl;

int arr_size = arr.size();

mergeSort(arr, 0, arr_size - 1);

cout << "Sorted array: ";
for (int num : arr) {
cout << num << " ";
}
cout << endl;

return 0;
}

0 comments on commit ba5531b

Please sign in to comment.