MCPcopy Create free account
hub / github.com/Tiwarishashwat/InterviewCodes / MergeSort

Class MergeSort

MergeSort.java:1–89  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1class MergeSort
2{
3 void merge(int arr[], int l, int m, int r)
4 {
5 int n1 = m - l + 1;
6 int n2 = r - m;
7 int L[] = new int[n1];
8 int R[] = new int[n2];
9
10 /*Copy data to temp arrays*/
11 for (int i = 0; i < n1; ++i)
12 L[i] = arr[l + i];
13 for (int j = 0; j < n2; ++j)
14 R[j] = arr[m + 1 + j];
15
16 /* Merge the temp arrays */
17 // Initial indexes of first and second subarrays
18 int i = 0, j = 0;
19 // Initial index of merged subarry array
20 int k = l;
21 while (i < n1 && j < n2)
22 {
23 if (L[i] <= R[j]) {
24 arr[k] = L[i];
25 i++;
26 }
27 else {
28 arr[k] = R[j];
29 j++;
30 }
31 k++;
32 }
33
34 /* Copy remaining elements of L[] if any */
35 while (i < n1) {
36 arr[k] = L[i];
37 i++;
38 k++;
39 }
40
41 /* Copy remaining elements of R[] if any */
42 while (j < n2) {
43 arr[k] = R[j];
44 j++;
45 k++;
46 }
47 }
48
49 // Main function that sorts arr[l..r] using
50 // merge()
51 void sort(int arr[], int l, int r)
52 {
53 if (l < r) {
54 // Find the middle point
55 int m =l+ (r-l)/2;
56
57 // Sort first and second halves
58 sort(arr, l, m);
59 sort(arr, m + 1, r);
60

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected