欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

c++归并排序

程序员文章站 2022-05-31 08:13:42
...
void merge(int a[], int first, int mid, int last)
{
	int* ptemp = new int[last - first + 1]{ 0 };
	int left_fitst = first;
	int left_last = mid;
	int right_first = mid + 1;
	int right_last = last;

	int k = 0;
	for (k = 0;left_fitst <= left_last && right_first <= right_last;k++)
	{
		if (a[left_fitst] <= a[right_first])
		{
			ptemp[k] = a[left_fitst++];

		}
		else
		{
			ptemp[k] = a[right_first++];
		}

	}
	if (left_fitst <= left_last)
	{
		for (int j = left_fitst;j <= left_last;j++)
		{
			ptemp[k] = a[j];
			k++;
		}


	}
	if (right_first <= right_last)
	{
		for (int j = right_first;j <= right_last;j++)
		{
			ptemp[k] = a[j];
			k++;
		}


	}
	for (int i = 0;i < last - first + 1;i++)
	{
		a[first + i] = ptemp[i];
	}
	delete[]ptemp;
}

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);
	}




}