# Merge Sort in ruby.
def merge_sort(array)
n = array.length
if n > 1
mid = n/2
lefthalf = array[0..mid-1]
righthalf = array[mid..n-1]
merge_sort lefthalf
merge_sort righthalf
i = j = k = 0
while i < lefthalf.length and j < righthalf.length
if lefthalf[i] < righthalf[j]
array[k] = lefthalf[i]
i = i+1
else
array[k] = righthalf[j]
j = j+1
end
k += 1
end
while i < lefthalf.length
array[k] = lefthalf[i]
i = i+1
k = k+1
end
while j < righthalf.length
array[k] = righthalf[j]
j = j+1
k = k+1
end
end
end
print array = [6,5,3,1,8,7,2,4]
merge_sort array
print array
def merge_sort(array)
n = array.length
if n > 1
mid = n/2
lefthalf = array[0..mid-1]
righthalf = array[mid..n-1]
merge_sort lefthalf
merge_sort righthalf
i = j = k = 0
while i < lefthalf.length and j < righthalf.length
if lefthalf[i] < righthalf[j]
array[k] = lefthalf[i]
i = i+1
else
array[k] = righthalf[j]
j = j+1
end
k += 1
end
while i < lefthalf.length
array[k] = lefthalf[i]
i = i+1
k = k+1
end
while j < righthalf.length
array[k] = righthalf[j]
j = j+1
k = k+1
end
end
end
print array = [6,5,3,1,8,7,2,4]
merge_sort array
print array
No comments:
Post a Comment