1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
|
#include <iostream>
#include <math.h>
using namespace std;
//Prints the array
template <class ItemType>
void print(ItemType values[], int numValues){
for(int i = 0; i < numValues; i++){
cout << values[i] << ", ";
}
cout << endl;
}
template <class ItemType>
void merge(ItemType a[], int low, int high, int mid){
int i, j, k, c[50];
i = low;
k = low;
j = mid + 1;
while (i <= mid && j <= high)
{
if (a[i] < a[j])
{
c[k] = a[i];
k++;
i++;
}
else
{
c[k] = a[j];
k++;
j++;
}
}
while (i <= mid)
{
c[k] = a[i];
k++;
i++;
}
while (j <= high)
{
c[k] = a[j];
k++;
j++;
}
for (i = low; i < k; i++)
{
a[i] = c[i];
}
}
//Splits the array recursively
template <class ItemType>
void MergeSort(ItemType values[], int low, int numValues){
int mid = ceil(numValues/2);
if(low < numValues){
ItemType temp[];
for(int i = 0; i < mid; i++){
temp[i] = values[i];
}
ItemType temp2[];
for(int i = mid+1; i < numValues; i++){
temp2[i] = values[i];
}
MergeSort(temp, mid, temp.length());
MergeSort(temp2, mid+1,temp2.length());
merge(values, low, numValues, mid);
}
return;
}
template <class ItemType>
int main(){
ItemType<int> val_array1[] = {43, 7, 10, 23, 38, 4, 19, 51, 66, 14};
ItemType<float> val_array2[] = {43.2, 7.1, 10.5, 3.9, 18.7, 4.2, 19.3, 5.7, 66.8, 14.4};
int numValues = 10;
cout << "The origional values of val_array1 are: " << print(val_array1, numValues);
//Sort ValArray1
MergeSort(val_array1, 0, numValues);
cout << "The sorted values of val_array1 are: " << print(val_array1, numValues);
cout << "The origional values of val_array2 are: " << print(val_array2, numValues);
//Sort ValArray2
MergeSort(val_array2, 0, numValues);
cout << "The sorted values of val_array2 are: " << print(val_array2, numValues);
return 0;
}
|