1 #include <iostream>
2 #include <vector>
3 #include <algorithm>
4 using namespace std;
5
6 void mergeLocal(int arr[], int low, int middle, int high)
7 {
8 int i, j, k; //i and j respectively represent the current position of the two subsequences to be merged
9 i = low;
10 j = middle + 1;
11 k = 0;
12 int b[high-low+1];
13 while(i<=middle&&j<=high)
14 {
15 if(arr[i]<=arr[j]) //the smaller subsequence is placed on the front
16 {
17 b[k] = arr[i];
18 k++;
19 i++;
20 }
21 else
22 {
23 b[k] = arr[j];
24 k++;
25 j++;
26 }
27 }
28 while(i<=middle) //if the subsequence of the leading position is not empty, copy the remainder to b
29 {
30 b[k] = arr[i];
31 k++;
32 i++;
33 }
34 while(j<=high) //if the subsequence of the back position is not empty, copy the remainder to b
35 {
36 b[k] = arr[j];
37 k++;
38 j++;
39 }
40 for(int p=low, h=0; p<=high; p++, h++)
41 {
42 arr[p] = b[h];
43 }
44 return;
45 }
46
47 void mergeSort(int a[], int low, int high)
48 {
49 int middle;
50 if(low<high)
51 {
52 middle = (low + high) / 2;
53 mergeSort(a, low, middle);
54 mergeSort(a, middle+1, high);
55 mergeLocal(a, low, middle, high);
56 }
57 return;
58 }
59 int main()
60 {
61 int a[] = {57, 68, 23, 90, 78, 32, 96, 13, 9, 45};
62 mergeSort(a, 0, 9);
63 for(int i=0; i<10; i++)
64 cout << a[i] << " ";
65 return 0;
66 }