merge algorithm

Two-way merge algorithm (C language)

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

void merge(int* data, int l,int m,int r)//l is the starting point of the left end, m is the middle point, and r is the right end point
{
	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);

}


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

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325074552&siteId=291194637