- Insertion sort:
def insertion(lis)
if lis.length == 0 then
[]
else
insert(lis[0], insertion(lis[1..lis.length-1]))
end
end
def insert(element, lis)
if lis.length==0 then
[element]
elsif element>lis[0] then
[lis[0]] + insert(element, lis[1..lis.length-1])
else
[element] + lis
end
end
x = [1,3,4,9,10,11,17]
y = [5, 2, 16, 20, 1, 30, 2]
print x, "\n"
print insert(6,x), "\n"
print insertion(y), "\n"
- List flattening
def flatten(lis)
if lis.length == 0 then
[]
elsif lis[0].class != Array then
[lis[0]] + flatten(lis[1..lis.length-1])
else
return flatten(lis[0]) + flatten(lis[1..lis.length-1])
end
end
y = [5, 2, [16, [20, 1]], 30, [[[2]]]]
print flatten(y), "\n"
- Partition function for quicksort
def partition(lis)
part(lis[1..lis.length-1], lis[0]) #((<= part) part (> part)) will be returned
end
def part(lis, pivot)
if lis.length==0 then
[[]] + [pivot] + [[]]
else
r = part(lis[1..lis.length-1], pivot) # recursive call which will
# return a list with structure
# ( (<= pivot) pivot (> pivot))
#r
if lis[0] > pivot then # add to > list
[r[0]] + [pivot] + [[lis[0]] + r[2]]
else # add to <= list
[[lis[0]] + r[0]] + r[1..r.length-1]
end
end
end
x = [6,3,4,9,10,1,7]
#OR from irb: partition(x) will print the answer as a list
print x, "\n"
#y = [1,2,10,12]
y = []
part(y,6)
#print partition(x), "\n"
Now, using the above partition function, try to write quicksort. A
soln is here but don't look until you have tried it!