Skip to content

Commit 1f11401

Browse files
authored
MergeSort
Merge sort is similar to the quick sort algorithm as it uses the divide and conquer approach to sort the elements. It is one of the most popular and efficient sorting algorithm. It divides the given list into two equal halves, calls itself for the two halves and then merges the two sorted halves. We have to define the merge() function to perform the merging
1 parent d6c7ffd commit 1f11401

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

MergeSortalgorithem.java

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
/* Function to merge the subarrays of a[] */
2+
void merge(int a[], int beg, int mid, int end)
3+
{
4+
int i, j, k;
5+
int n1 = mid - beg + 1;
6+
int n2 = end - mid;
7+
8+
int LeftArray[n1], RightArray[n2]; //temporary arrays
9+
10+
/* copy data to temp arrays */
11+
for (int i = 0; i < n1; i++)
12+
LeftArray[i] = a[beg + i];
13+
for (int j = 0; j < n2; j++)
14+
RightArray[j] = a[mid + 1 + j];
15+
16+
i = 0, /* initial index of first sub-array */
17+
j = 0; /* initial index of second sub-array */
18+
k = beg; /* initial index of merged sub-array */
19+
20+
while (i < n1 && j < n2)
21+
{
22+
if(LeftArray[i] <= RightArray[j])
23+
{
24+
a[k] = LeftArray[i];
25+
i++;
26+
}
27+
else
28+
{
29+
a[k] = RightArray[j];
30+
j++;
31+
}
32+
k++;
33+
}
34+
while (i<n1)
35+
{
36+
a[k] = LeftArray[i];
37+
i++;
38+
k++;
39+
}
40+
41+
while (j<n2)
42+
{
43+
a[k] = RightArray[j];
44+
j++;
45+
k++;
46+
}
47+
}

0 commit comments

Comments
 (0)