Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added mergesort cpp in the merge sort folder #874

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 84 additions & 0 deletions merge_sort/merge_sort.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
#include <iostream>
using namespace std;

void merge(int arr[], int s, int e, int mid) {
int temp[e - s + 1];
int i = s;
int j = mid + 1;
int k = 0;

// Merge two sorted arrays into a temporary array
while (i <= mid && j <= e) {
if (arr[i] <= arr[j]) {
temp[k] = arr[i];
k++;
i++;
} else {
temp[k] = arr[j];
k++;
j++;
}
}

// Copy remaining elements from the first subarray, if any
while (i <= mid) {
temp[k] = arr[i];
k++;
i++;
}

// Copy remaining elements from the second subarray, if any
while (j <= e) {
temp[k] = arr[j];
k++;
j++;
}

// Copy the merged elements from the temporary array back to the original array
for (k = 0, i = s; k < e - s + 1; k++, i++) {
arr[i] = temp[k];
}
}

void mergesort(int arr[], int s, int e) {
if (s >= e) {
return;
}

// Calculate the middle index
int mid = s + (e - s) / 2;

// Recursively sort the first and second halves
mergesort(arr, s, mid);
mergesort(arr, mid + 1, e);

// Merge the sorted halves
merge(arr, s, e, mid);
}
int main() {
int n;

// user input
cout << "Enter the size of the array: ";
cin >> n;
int arr[n];
cout << "Enter " << n << " elements: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}

// Call the merge sort function to sort the array
mergesort(arr, 0, n - 1);

// Print the sorted array
cout << "Sorted array: ";
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}

return 0;
}