Merge函数写得乱了,听着鞭炮声敲代码= =
#include <stdio.h>
#include <stdlib.h>
int FindStep(int sorted[], int step,int n);
void Merge(int sorted[], int step,int NextStep[],int n);
int main()
{
int n, i = 0, Isinsertion = 1, Pos;
scanf("%d", &n);
int *data = (int*)malloc(sizeof(int)*n);
int *sorted = (int*)malloc(sizeof(int)*n);
while (i < n)
scanf("%d", &data[i++]);
i = 0;
while (i < n)
scanf("%d", &sorted[i++]);
/*判断是否插入排序*/
for (i = 0; i < n; i++)
if (sorted[i + 1] < sorted[i])
break;
Pos = i;
while (++i<n)
if (data[i] != sorted[i]) {
Isinsertion = 0;
break;
}
if (!Isinsertion) {
printf("Merge Sort\n");
int step,*Nextstep;
Nextstep = (int*)malloc(sizeof(int)*n);
for (step = 2; step <=n ; step *= 2)
if (FindStep(sorted, step,n))
break;
step /= 2;
Merge(sorted, step, Nextstep,n);
free(sorted);
sorted = Nextstep;
}
else {
printf("Insertion Sort\n");
int X = sorted[Pos + 1];
i = Pos;
while (sorted[i] > X) {
sorted[i + 1] = sorted[i];
i--;
}
sorted[i + 1] = X;
}
for (i = 0; i < n - 1; i++)
printf("%d ", sorted[i]);
printf("%d", sorted[n - 1]);
free(sorted);
return 0;
}
int FindStep(int sorted[], int step,int n)
{
int i;
for (i = 0; i < n; i++)
if (i%step)
if (sorted[i] < sorted[i - 1])
return 1;
return 0;
}
void Merge(int sorted[], int step,int NextStep[],int n)
{
int L=0, R=step, LeftEnd=R-1,RightEnd=2*step-1,i,j,k;
while (L < n) {
i = L; j = R; k = L;
while (i <= LeftEnd&&j <= RightEnd)
if (sorted[i] < sorted[j])
NextStep[k++] = sorted[i++];
else NextStep[k++] = sorted[j++];
while (i <= LeftEnd)
NextStep[k++] = sorted[i++];
while (j <= RightEnd)
NextStep[k++] = sorted[j++];
L = RightEnd + 1;
LeftEnd = L + step - 1;
if (LeftEnd > n - 1)
LeftEnd = n - 1;
R = LeftEnd + 1;
if (R > n - 1) {
R = n+1;
RightEnd = n;
}
else {
RightEnd = R + step - 1;
if (RightEnd > n - 1)
RightEnd = n - 1;
}
}
}