码迷,mamicode.com
首页 > 编程语言 > 详细

归并算法

时间:2018-04-30 23:27:46      阅读:198      评论:0      收藏:0      [点我收藏+]

标签:merge   class   oid   style   include   二路归并   eof   ++   归并   

二路归并算法(c语言)

#include <stdio.h>
#include <stdlib.h>

void merge(int* data, int l,int m,int r)//l 左端起始点,m为中间点,r为右端点
{
	int left = l;
	int right = m;
	int n = r -l;
	int* tmp = (int*) malloc(sizeof(int)*n);
	int count = 0;

	while (left < m && right <r )
	{
		if (data[left] <= data[right])
		{
			tmp[count] = data[left];
			left ++;
		} 
		else
		{
			tmp[count] = data[right];
			right ++;
		}
		count ++;
	}

	while (left < m)
	{
		tmp[count] = data[left];
		count++;
		left++;
	}

	while (right < r)
	{
		tmp[count] = data[right];
		count++;
		right++;
	}


	for (int i = 0; i < r; i++)
	{
		data[i] = tmp[i];
	}
	free(tmp);

}


int main()
{
	int data[12] = {1,3,5,6,9,12,0,2,3,4,8,88};
	merge(data,0,6,12);
	for (int i = 0; i < 12; i++)
	{
		printf("%d ",data[i]);
	}
	return 0;
}

  

归并算法

标签:merge   class   oid   style   include   二路归并   eof   ++   归并   

原文地址:https://www.cnblogs.com/jackzone/p/8975038.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!