算法导论——2.3-2无哨兵情况下的归并排序

没有哨兵时,可以设置一个判断,只要2个分数组的一个到达底端就把另一个的后续元素赋给原数组。具体如下:

#include

using namespace std;
const int sentry = 999999;

void Merge(int ia[], size_t p, size_t q, size_t r)
{
	int a1[10], a2[10];
	size_t len1 = q - p + 1, len2 = r - q;
	for (int i = 0; i if (b !=len1 && c !=len2)        //只有在b没有到达len1且c没有到达len2时才会将小的值给ia
		{
			if (a1[b] >= a2[c])
				ia[i] = a2[c++];
			else
				ia[i] = a1[b++];
		}
		else {							 
			if (b == len1)			//如果b取到len1,那就把a2数组一次赋给ia
				for (int j = c; j < len2; ++j)
					ia[i] = a2[j];
			if (c == len2)			//如果c取到len2,那就把a1数组一次赋给ia
				for (int j = b; i < len1; ++j)
					ia[i] = a1[j];
		}
	}
}
void Merge_sort(int ia[], size_t p, size_t r)
{
	if (p < r)
	{
		int q = (p + r) / 2;
		Merge_sort(ia, p, q);
		Merge_sort(ia, q + 1, r);
		Merge(ia, p, q, r);
	}
}
int main()
{
	int a[20];
	int n;
	cout << "input the size of array:" << endl;
	cin >> n;
	for (int i = 0; i < n; ++i)
		cin >> a[i];								//input array
	Merge_sort(a, 0, n - 1);
	for (int i = 0; i < n; ++i)
		cout << a[i] << " ";
	cout << endl;
	return 0;
}






你可能感兴趣的:(算法导论)