其他分享
首页 > 其他分享> > 归并排序

归并排序

作者:互联网

归并排序

1.先将数组进行二分

2,对每一部分进行排序,然后合并

#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<vector>
#include<queue>
using namespace std;

int a[10] = { 0,423,365,567,994,234,5,54,234,24 };
void merge_sort(int l, int r);
int main()
{
	merge_sort(1, 9);
	for (int i = 1; i <= 9; i++)
		cout << a[i] << " ";
	return 0;
}

void merge_sort(int l, int r)
{
	if (l == r)
		return;
	int mid = (l + r) / 2;
	merge_sort(l, mid);//将数组分成左部分
	merge_sort(mid + 1, r);//将数组分成右半部分
//将左右部分合并操作
	int temp[10], top = l;
	for (int i = l, j = mid + 1; i <= mid || j <= r;)
	{
		if (i > mid)
		{
			while (j <= r)
			{
				temp[top] = a[j]; j++; top++;
			}
			break;
		}
		if (j > r)
		{
			while (i <= mid)
			{
				temp[top] = a[i]; i++; top++;
			}
			break;
		}
		if (a[i] <= a[j])
		{
			temp[top] = a[i]; i++;
		}
		else
		{
			temp[top] = a[j]; j++;
		}
		top++;
	}
	for (int i = l; i <= r; i++)
		a[i] = temp[i];
}

标签:sort,归并,排序,int,merge,234,include
来源: https://www.cnblogs.com/wz021001/p/15536087.html