这个就开始考验脑袋了
下面说一下代码实现思路,不然很难下手
首先要想好合并和分治
先写好其中一项,比如这次我是先写合并,那么分治的时候就要将就着合并的参数进行编码
void merge_Sequnece(int a[], int first, int mid, int last, int temp[])
{
int i = first, j = mid + 1;
int m = mid, n = last;
int k = 0;
while (i <= m && j <= n)
{
if (a[i] <= a[j])
temp[k++] = a[i++];
else
temp[k++] = a[j++];
}
while (i <= m)
temp[k++] = a[i++];
while (j <= n)
temp[k++] = a[j++];
for (i = 0; i < k; i++)
a[first + i] = temp[i];
}
思路很简单,为了实现在O(2n)的空间条件下进行合并,我们申请了一个临时数组作为中间变量,在合并的时候才用堆叠合并
注意到为了使得思考清晰,用的是<=而非<
void Divide_Sequence(int *S,int first, int last, int *temp){
if (first < last){
int mid = (first + last) / 2;
Divide_Sequence(S, first, mid, temp);
Divide_Sequence(S, mid + 1, last, temp);
merge_Sequnece(S, first, mid, last, temp);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int *temp = new int[6];
int S[5] = { 31, 41, 59, 26, 41 };
Divide_Sequence(S, 0, 4, temp);
for (int i = 0; i < 5; i++){
std::cout << S[i] << " ";
}
system("pause");
delete []temp;
return 0;
}
调用和分治