merge_sort problem

H

Haofei

here is the merge_sort i write in ruby. but it doesn't produce the
right answer, i can't find where the problem is . thanks in advance

def merge(a, p, q, r)
a1=a[0..(q-p)]
a2=a[(q-p+1)..r]
a1<<99999999
a2<<99999999
i=j=0
for k in (p..r)
if a1<=a2[j]
a[k]=a1
i=i+1
else
a[k]=a2[j]
j=j+1
end
end
end

def merge_sort(a,p,r)
if p<r
q =(p+r)/2
merge_sort(a,p,q)
merge_sort(a,q+1,r)
merge(a,p,q,r)
end
end

a=[]
10.times {a<<rand(10)}
p a
merge_sort(a,0,9)
p a
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,813
Messages
2,569,696
Members
45,481
Latest member
Arnulfo32P

Latest Threads

Top