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 97
|
#include <iostream>
using namespace std;
void merge(int *, int, int, int);
void merge(int *a, int low, int high, int mid, int mid2)
{
int i, j, k, l, c[50];
i = low;
k = low;
j = mid + 1;
l = mid2 + 1;
while (i <= mid && j <= mid2 && l <= high)
{
if (a[i] < a[j])
{
c[k] = a[i];
k++;
i++;
}
else if (a[j] < a[l])
{
c[k] = a[j];
k++;
j++;
}
else
{
c[k] = a[l];
k++;
l++;
}
}
while (i <= mid)
{
c[k] = a[i];
k++;
i++;
}
while (j <= mid2)
{
c[k] = a[j];
k++;
j++;
}
while (l <= high)
{
c[k] = a[l];
k++;
l++;
}
for (i = low; i < k; i++)
{
a[i] = c[i];
}
}
void mergesort(int *a, int low, int high)
{
int mid;
int mid2;
if (low < high)
{
mid = (low + high) / 3;
mid2 = 2 * ((low + high) / 3);
mergesort(a, low, mid);
mergesort(a, mid + 1, mid2);
mergesort(a, mid2 + 1, high);
merge(a, low, mid, mid2, high);
}
return;
}
int main()
{
int a[20], i;
cout << "Enter 5 elements to sort" << endl;
for (i = 0; i < 5; i++)
{
cin >> a[i];
}
mergesort(a, 0, 4);
cout << "Sorted list: " << endl;
for (i = 0; i < 5; i++)
{
cout << a[i] << endl;
}
system("pause");
return 0;
}
|