自己错的程序mergesort放在各个论坛上寻求答案,结果三天没人回复。想来也是高手无暇,菜鸟无语。于是自己静下心来,仔细看了一下,还是标号弄错了。既然开了两个数组,那么数据拷贝进去后,标号应该是当前数组的,结果用了原来数组的标号,导致错误。这是修改后的源码:
//
mergesort
#include
<
iostream
>
using
namespace
std;
int
merge(
int
A[],
int
p,
int
q,
int
r)
{
int
n1
=
q
-
p
+
1
;
int
n2
=
r
-
q;
int
*
L
=
new
int
[n1];
int
*
R
=
new
int
[n2];
for
(
int
i
=
0
;i
<
n1;
++
i)
L[i]
=
A[p
+
i];
for
(
int
j
=
0
;j
<
n2;
++
j)
R[j]
=
A[q
+
1
+
j];
i
=
0
;j
=
0
;
int
k
=
p;
while
(i
<
n1
&&
j
<
n2)
{
if
(L[i]
<=
R[j])
{A[k
++
]
=
L[i
++
];}
else
{A[k
++
]
=
R[j
++
];}
}
while
(i
<
n1)
{
A[k
++
]
=
L[i
++
];}
while
(j
<
n2)
{
A[k
++
]
=
R[j
++
];}
return
(
0
);
}
int
mergesort(
int
A[],
int
p,
int
r)
{
int
q;
if
(p
<
r)
{
q
=
(p
+
r)
/
2
;
mergesort(A,p,q);
mergesort(A,q
+
1
,r);
merge(A,p,q,r);
}
return
(
0
);
}
int
main()
{
int
b[
6
]
=
{
11
,
65
,
53
,
78
,
38
,
63
}
;
mergesort(b,
0
,
5
);
for
(
int
i
=
0
;i
<
6
;
++
i)
cout
<<
b[i]
<<
'
\t
'
;
return
(
0
);
}
小小的错误,找了我半天