首页 > 学院 > 开发设计 > 正文

归并排序

2019-11-14 13:04:35
字体:
来源:转载
供稿:网友

先一直拆分。拆成很小的段 再拼回来 拼的时候顺便把序排了

#include <iostream>using namespace std;int a[5] = { 25, 2, 33343, 5, 1 };void merge(int *a, int first, int mid, int last){	int *b = new int[last - first+1];	int k = 0;	int a1 = first;	int a2 = mid;	int b1 = mid + 1;	int b2 = last;	while (a1<=a2&&b1<=b2)//如果是1 5   2  25比较。就是1 2 比较 依次插入1 2 5 剩下25 在while外面会把剩下的数加入	{		if (a[a1] <a[b1])			b[k++] = a[a1++];		else			b[k++] = a[b1++];	}	if (a1<=a2)//剩下a1这边一个 如果不是a1应该大于a2	{		for (int i = a1; i <= a2; i++)			b[k++] = a[i];	}	if (b1 <=b2)//剩下b1这边一个	{		for (int i = b1; i <= b2; i++)			b[k++] = a[i];	}	for (int  i = 0; i < last-first+1; i++)	{		a[first+i] = b[i];	}	delete b;}void merge_sort(int *a,int first,int last){	int mid = 0;	if (first < last)	{		mid = (first + last) / 2;//拆开		merge_sort(a, first, mid);		merge_sort(a, mid + 1, last);		merge(a, first, mid, last);	}}int main(){	merge_sort(a, 0, 4);	for (int i = 0; i < 5; i++)		cout << a[i]<<" ";	system("pause");}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表