1
+ #include < iostream>
2
+ using namespace std ;
3
+
4
+ // Merges two sorted subarrays of A[].
5
+ // First sorted subarray is A[l..m].
6
+ // Second sorted subarray is A[m+1..r].
7
+ // You might want to call this function in function mergeSort().
8
+ void merge (int A[], int l, int m, int r)
9
+ {
10
+ int i = 0 ; // cursor in leftArray[]
11
+ int j = 0 ; // cursor in rightArray[]
12
+ int k = l; // cursor in A[]
13
+
14
+ int sizeOfRight = r - m; // calculates sizes of subarrays
15
+ int sizeOfLeft = m - l + 1 ;
16
+
17
+ int leftArray[sizeOfLeft]; // creates temporary arrays
18
+ int rightArray[sizeOfRight];
19
+
20
+ for (i; i < sizeOfLeft; i++) { // fills leftArray[]
21
+ leftArray[i] = A[k];
22
+ k++;
23
+ }
24
+
25
+ for (j; j < sizeOfRight; j++) { // fills rightAray[]
26
+ rightArray[j] = A[k];
27
+ k++;
28
+ }
29
+
30
+ i = 0 ; // reseting cursors
31
+ j = 0 ;
32
+ k = l;
33
+
34
+ // merging contents of arrays
35
+ while (i < sizeOfLeft && j < sizeOfRight) {
36
+ if (leftArray[i] <= rightArray[j]) {
37
+ A[k] = leftArray[i];
38
+ i++;
39
+ k++;
40
+ }
41
+ else {
42
+ A[k] = rightArray[j];
43
+ j++;
44
+ k++;
45
+ }
46
+ }
47
+
48
+ // finishes merging the remaining array
49
+ while (i < sizeOfLeft) {
50
+ A[k] = leftArray[i];
51
+ i++;
52
+ k++;
53
+ }
54
+
55
+ while (j < sizeOfRight) {
56
+ A[k] = rightArray[j];
57
+ j++;
58
+ k++;
59
+ }
60
+ }
61
+
62
+ // using mergeSort to sort sub-array A[l..r]
63
+ // l is for left index and r is right index of the
64
+ // sub-array of A[] to be sorted
65
+ void mergeSort (int A[], int l, int r)
66
+ {
67
+ int first = l;
68
+ int last = r;
69
+
70
+ if (first == last) // base case
71
+ return ;
72
+ else {
73
+ int middle = (first + last) / 2 ; // general case
74
+
75
+ mergeSort (A,first, middle);
76
+ mergeSort (A, middle + 1 , last);
77
+
78
+ merge (A, first, middle, last);
79
+ }
80
+ }
81
+
82
+ int main ()
83
+ {
84
+ cout << " Please enter the length (number of elements) of the input array: " ;
85
+ int n;
86
+ cin >> n;
87
+
88
+ if (n <= 0 ) {
89
+ cout << " Illegal input array length!" << endl;
90
+ return 0 ;
91
+ }
92
+
93
+ int * A = new int [n];
94
+
95
+ cout << " Please enter each element in the array" << endl;
96
+ cout << " (each element must be an integer within the range of int type)." << endl;
97
+ for (int i=0 ; i<n; i++) {
98
+ cout << " A[" << i << " ] = " ;
99
+ cin >> A[i];
100
+ }
101
+
102
+ cout << " Given array A[] is: " ;
103
+ for (int i=0 ; i<n-1 ; i++)
104
+ cout << A[i] << " ," ;
105
+ cout << A[n-1 ] << endl;
106
+
107
+
108
+ mergeSort (A, 0 , n-1 );
109
+
110
+ cout << " After mergeSort, sorted array A[] is: " ;
111
+ for (int i=0 ; i<n-1 ; i++)
112
+ cout << A[i] << " ," ;
113
+ cout << A[n-1 ] << endl;
114
+
115
+
116
+ delete [] A;
117
+ return 0 ;
118
+ }
0 commit comments