Skip to content

Commit 76055bd

Browse files
Merge pull request #110 from sourishphate/master
MERGE SORT ALGORITHM
2 parents ce7329d + 2115b64 commit 76055bd

File tree

1 file changed

+112
-0
lines changed

1 file changed

+112
-0
lines changed

CodeBase/merge_sort.cpp

+112
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,112 @@
1+
/**
2+
* PROBLEM: Merge Sort in C++
3+
* AUTHOR: sourishphate
4+
**/
5+
6+
#include <iostream>
7+
#include <vector>
8+
9+
using namespace std;
10+
11+
/**
12+
* This function merges two sorted halves of an array
13+
*
14+
* @param A: the array to be sorted
15+
* @param low: starting index of the first half
16+
* @param mid: ending index of the first half
17+
* @param high: ending index of the second half
18+
**/
19+
void merge(vector<int>& A, int low, int mid, int high) {
20+
int n1 = mid - low + 1; // Length of first half
21+
int n2 = high - mid; // Length of second half
22+
23+
vector<int> L(n1); // Create temp arrays
24+
vector<int> R(n2);
25+
26+
// Copy data to temporary arrays L[] and R[]
27+
for (int i = 0; i < n1; i++) {
28+
L[i] = A[low + i];
29+
}
30+
for (int j = 0; j < n2; j++) {
31+
R[j] = A[mid + 1 + j];
32+
}
33+
34+
int i = 0; // Initial index of first subarray
35+
int j = 0; // Initial index of second subarray
36+
int k = low; // Initial index of merged subarray
37+
38+
while (i < n1 && j < n2) {
39+
if (L[i] <= R[j]) {
40+
A[k] = L[i];
41+
i++;
42+
} else {
43+
A[k] = R[j];
44+
j++;
45+
}
46+
k++;
47+
}
48+
49+
// Copy the remaining elements of L[], if any
50+
while (i < n1) {
51+
A[k] = L[i];
52+
i++;
53+
k++;
54+
}
55+
56+
// Copy the remaining elements of R[], if any
57+
while (j < n2) {
58+
A[k] = R[j];
59+
j++;
60+
k++;
61+
}
62+
}
63+
64+
/**
65+
* This function sorts an array using merge sort algorithm
66+
*
67+
* @param A: the array to be sorted
68+
* @param p: starting index
69+
* @param r: ending index
70+
**/
71+
void mergeSort(vector<int>& A, int p, int r) {
72+
if (p < r) {
73+
int q = (p + r) / 2; // Find the midpoint
74+
mergeSort(A, p, q); // Sort first half
75+
mergeSort(A, q + 1, r); // Sort second half
76+
merge(A, p, q, r); // Merge the two sorted halves
77+
}
78+
}
79+
80+
/**
81+
* This function prints the array
82+
*
83+
* @param A: the array to print
84+
**/
85+
void printArray(const vector<int>& A) {
86+
for (int val : A) {
87+
cout << val << " ";
88+
}
89+
cout << endl;
90+
}
91+
92+
int main() {
93+
int size;
94+
cout << "Enter the size of the array: ";
95+
cin >> size;
96+
97+
vector<int> A(size);
98+
cout << "Enter the elements of the array:\n";
99+
for (int i = 0; i < size; i++) {
100+
cin >> A[i];
101+
}
102+
103+
cout << "Unsorted array: ";
104+
printArray(A);
105+
106+
mergeSort(A, 0, A.size() - 1);
107+
108+
cout << "Sorted array: ";
109+
printArray(A);
110+
111+
return 0;
112+
}

0 commit comments

Comments
 (0)