0% found this document useful (0 votes)
15 views1 page

Mergesort CPP

The document contains a C++ implementation of the merge sort algorithm. It includes functions for merging two halves of an array, performing the merge sort recursively, and printing the array. The main function demonstrates sorting an example array and outputs the original and sorted arrays.

Uploaded by

Arnav Vikas Garg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views1 page

Mergesort CPP

The document contains a C++ implementation of the merge sort algorithm. It includes functions for merging two halves of an array, performing the merge sort recursively, and printing the array. The main function demonstrates sorting an example array and outputs the original and sorted arrays.

Uploaded by

Arnav Vikas Garg
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

11/14/23, 10:24 AM mergesort.

cpp

mergesort.cpp

1 #include <iostream>
2 using namespace std;
3 void merge(int arr[], int l, int m, int r) {
4 int n1 = m - l + 1;
5 int n2 = r - m;
6 int L[n1], R[n2];
7 for (int i = 0; i < n1; i++)
8 L[i] = arr[l + i];
9 for (int j = 0; j < n2; j++)
10 R[j] = arr[m + 1 + j];
11 int i = 0, j = 0, k = l;
12 while (i < n1 && j < n2) {
13 if (L[i] <= R[j]) {
14 arr[k] = L[i];
15 i++;
16 } else {
17 arr[k] = R[j];
18 j++;
19 }
20 k++;
21 }
22 while (i < n1) {
23 arr[k] = L[i];
24 i++;
25 k++;
26 }
27 while (j < n2) {
28 arr[k] = R[j];
29 j++;
30 k++;
31 }
32 }
33 void mergeSort(int arr[], int l, int r) {
34 if (l < r) {
35 int m = l + (r - l) / 2;
36 mergeSort(arr, l, m);
37 mergeSort(arr, m + 1, r);
38 merge(arr, l, m, r);
39 }
40 }
41 void printArray(int arr[], int size) {
42 for (int i = 0; i < size; i++)
43 cout << arr[i] << " ";
44 cout << endl;
45 }
46 int main() {
47 int arr[] = {121, 7, 1, 5, 659, 24, 89, 10};
48 int arr_size = sizeof(arr) / sizeof(arr[0]);
49 cout << "Original array: ";
50 printArray(arr, arr_size);
51 mergeSort(arr, 0, arr_size - 1);
52 cout << "Sorted array: ";
53 printArray(arr, arr_size);
54 return 0;
55 }
56

localhost:49757/066fd858-aad8-4e3f-986f-90182343871c/ 1/1

You might also like