这是文件
12,221,311,4,5,6,71,22
输出
('L:',['12','221','311','4'])
('R:',['5','6','71','22'])
('L,R','12','5')
假
******这个条件给出了错误的结果(如果12 <5),它仍然在这个循环中
代码:
def merge(Array,start,end,mid):
A=Array
p=start
q=end
r=mid
size1=q-p+1
size2=r-q
print("size1:", size1)
print("size2:", size2)
L=[None]*size1
R=[None]*size2
#print("L[]", L)
for i in range(size1):
print("i:", i)
L[i]=A[p+i]
print("L:", L)
for j in range(size2):
R[j]=A[q+j+1]
print("R:", R)
#L[size1+1]=99999
#R[size2+1]=99999
i,j=0,0
B=[None]*(r+1)
print("L,R", L[0],R[0])
**#Getting a error here...the condition down is giving wrong answer...**
if L[0]<R[0]:
print("false")
for k in range(p,r+1,1):
print("i:",i)
print("j:",j)
if L[i]<=R[j]:
B[k]=L[i]
i=i+1
else:
B[k]=R[j]
j=j+1
print(B)
def merge_sort(Array,start,end):
p=start
r=end
A=Array
if p<r:
print("P:",p)
print("R:",r)
q=(p+r)/2
print("Q:",q)
#merge_sort(A,p,q)
#merge_sort(A,q+1,r)
merge(A,p,q,r)
def main():
p=0
f = open('input.txt', 'r')
A=[]
#B=[]
for ch in f:
A=ch.split(',')
f.close()
print("Unsorted list")
print(A)
r=len(A)
merge_sort(A,p,r-1)
if __name__=="__main__":
main()
答案 0 :(得分:0)
这是因为你正在比较字符串。
将主要功能更改为:
def main():
p=0
f = open('input.txt', 'r')
A=[]
#B=[]
for ch in f:
A=ch.split(',')
f.close()
A = [int(x) for x in A] #<--- Convert values to ints
print("Unsorted list")
print(A)
r=len(A)
merge_sort(A,p,r-1)
新输出:
未排序的列表
[12,221,311,4,5,6,71,22]
(&#39; P:&#39;,0)
(&#39; R:&#39;,7)
(&#39;问:&#39;,3)
(&#39; size1:&#39;,4)
(&#39; size2:&#39;,4)
(&#39; i:&#39;,0)
(&#39; i:&#39;,1)
(&#39; i:&#39;,2)
(&#39; i:&#39;,3)
(&#39; L:&#39;,[12,221,311,4])
(&#39; R:&#39;,[5,6,71,22])
(&#39; L,R&#39;,12,5)
(&#39; i:&#39;,0)
(&#39; j:&#39;,0)
(&#39; i:&#39;,0)
(&#39; j:&#39;,1)
(&#39; i:&#39;,0)
(&#39; j:&#39;,2)
(&#39; i:&#39;,1)
(&#39; j:&#39;,2)
(&#39; i:&#39;,1)
(&#39; j:&#39;,3)
(&#39; i:&#39;,1)
(&#39; j:&#39;,4)
(然后它失败了)
Traceback (most recent call last):
File "test.py", line 68, in <module>
main()
File "test.py", line 65, in main
merge_sort(A,p,r-1)
File "test.py", line 51, in merge_sort
merge(A,p,q,r)
File "test.py", line 31, in merge
if L[i]<=R[j]:
IndexError: list index out of range