diff --git a/DSA_Codesheet/Cpp/MergeSort.cpp b/DSA_Codesheet/Cpp/MergeSort.cpp new file mode 100644 index 0000000..0ff563e --- /dev/null +++ b/DSA_Codesheet/Cpp/MergeSort.cpp @@ -0,0 +1,83 @@ +#include + +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; +}