/*
1.首先将数据分解,最小单位为1 ,意味着有序数组
2.将分解后的数组,有序的合并
*/
#include<iostream>
using namespace std;
void merger(int a[], int first, int mid, int last, int temp[]);
void divide_and_merger(int a[], int first, int last, int temp[]);
int main()
{
int a[10] = { 6, 2, 5, 1, 4, 9, 3, 7, 10, 8 } , b[10];
for (int i = 0; i < 10; i++)
{
cout << a[i] << " ";
}
cout << endl;
divide_and_merger(a,0,9 ,b);
cout << endl << "排序后的顺序" << endl;
for (int i = 0; i < 10; i++)
{
cout << b[i] << " ";
}
system("pause");
return 0;
}
void merger(int a[], int first,int mid ,int last , int temp[])
{
cout << "first = " <<first <<" mid = "<<mid<<" last =" << last << endl;
int f = first,
m1 = mid ,
m2 = mid+1,
l = last,
k = first;
/*if (f == m1)
{
if (a[f] < a[l])
{
temp[f] = a[f];
temp[l] = a[l];
}
else
{
temp[f] = a[l];
temp[l] = a[f];
}
}
else*/
{
while (f <= m1 && m2 <= l)
{
if (a[f] < a[m2])
{
temp[first] = a[f];
first++;
f++;
}
else
{
temp[first] = a[m2];
first++;
m2++;
}
}
if (m2 <= l)
{
for (int i = m2; i <= l; i++)
{
temp[first] = a[i];
first++;
}
}
if (f <= m1)
{
for (int i = f; i <= m1; i++)
{
temp[first] = a[i];
first++;
}
}
}
for (int i = 0; i <= l; i++)
{
a[i] = temp[i];
}
}
void divide_and_merger(int a[], int first, int last, int temp[])
{
//cout << " first = " <<first <<" last =" << last <<endl;
if (first < last)
{
//将数据分解
int mid = (first + last) / 2;
divide_and_merger(a, first, mid, temp);
divide_and_merger(a, mid + 1, last, temp);
merger(a, first, mid, last, temp);
}
}
归并排序
最新推荐文章于 2023-12-11 10:45:47 发布