#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#define MAX 100
int b;
int arr[MAX],tearr[MAX];
void merge(int a[],int t[],int lhead, int rtail)
{
int lt, k, mid, rt;
mid = (lhead+rtail)/2;
lt = k = lhead;
rt = mid+1;
if (rtail-lhead <= 0)
{
goto tailsort;
}
merge(a,t, lhead,mid);
merge(a,t, mid+1,rtail);
while (lt<=mid && rt<=rtail)
{
t[k++] = (a[lt]<=a[rt])?a[lt++]:a[rt++];
}
while (lt<=mid)
{
t[k++] = a[lt++];
}
while (rt<=rtail)
{
t[k++] = a[rt++];
}
for (b=0; b<MAX;b++)
{
a[b] = t[b];
}
tailsort: ;
}
void main()
{
int head,tail,i;
for (i=0; i<MAX;i++)
{
arr[i] = rand();
}
for(i=0; i<MAX; i++) printf("%d ",arr[i]);
system("pause");
head = 0; tail = MAX;
merge(arr,tearr, head, MAX-1);
for (i=0; i<MAX;i++)
{
arr[i] = tearr[i];
}
for (i=0; i<MAX;i++)
{
printf(" %d",arr[i]);
}
system("pause");
}
樓主我照抄了您的代碼運行後,發現好多數據都清零了,對著您的代碼我思考實驗了半天,最終終於找到問題所在,以下是代碼【在您的代碼基礎上稍有更改,經我測驗沒有問題,請驗證】
#include
#include
#include
#define MAX 100
int b;
int arr[MAX],tearr[MAX];
void merge(int a[],int t[],int lhead, int rtail)
{
int lt, k, mid, rt;
mid = (lhead+rtail)/2;
lt = k = lhead;
rt = mid+1;
if (rtail-lhead <= 0)
{
goto tailsort;
}
merge(a,t, lhead,mid);
merge(a,t, mid+1,rtail);
while (lt<=mid && rt<=rtail)
{
t[k++] = (a[lt]<=a[rt])?a[lt++]:a[rt++];
}
while (lt<=mid)
{
t[k++] = a[lt++];
}
while (rt<=rtail)
{
t[k++] = a[rt++];
}
for (b=0; b<MAX;b++)
{
a[b] = t[b];
}
tailsort: ;
}
void main()
{
int i;
for (i=0; i<MAX;i++)
{
arr[i] = rand();
}
for(i=0; i<MAX; i++) printf("%d ",arr[i]);
system("pause");
/*****問題出在這裡******/
for (i=0; i<MAX;i++)
{
tearr[i] = arr[i];
}
/*****加上這個循環即可,至於為什麼,樓主請自行考慮!******/
merge(arr,tearr, 0, MAX-1);
for (i=0; i<MAX;i++)
{
printf(" %d",arr[i]);
}
system("pause");
}