- Insertion sort:
sub insertionsort {
if (scalar(@_) == 0) {
return ();
}
else {
return insert($_[0], insertionsort(@_[1..$#_]));
}
}
sub insert {
my ($element, @lis) = @_;
my @templis;
if (scalar(@lis) == 0) {
return ($element);
} elsif ($element > $lis[0]) {
@templis = insert($element, @lis[1..$#lis]);
unshift(@templis, $lis[0]);
return @templis;
} else {
unshift(@lis, $element);
return @lis;
}
}
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
####################################################
# Not implemented in Perl...How do you recognize a list/array type in Perl?
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!