In: Computer Science
Programming assignment 9
Write a function sortWords(array) that does the following:
1. Takes as an input a cell array of strings consisting of letters
only. (1 pts)
2. Returns a cell array with all the strings in alphabetical order.
(5 pts)
3. The function should ignore whether letters are lower case or
upper case. (2 pts)
Test your function with the following: (2 pts)
>>
sorted=sortWords({’Hello’,’hell’,’abc’,’aa’,’aza’,’aab’,’AaBb’,’a’})
sorted =
’a’ ’aa’ ’aab’ ’AaBb’ ’abc’ ’aza’ ’hell’ ’Hello’
Note: Your function may not contain any built-in MATLAB function(s)
that deal with sorting or finding minimum values. If your function
does use these built-in functions, up to 8 points may be deducted
from your total.
Hint: Use the program sharkSort(vec) as a starting point and amend
it so that it works for this programming assignment. For example
your function could start as follows (fill in the blanks as
necessary):
function sortedarray=sortWords(array) sortedarray={}; while
~isempty(array) [m,pos]=findSmallest(array); array(pos)=[];
sortedarray=[sortedarray m]; end
function [m,pos]=findSmallest(array) m = ...; pos=1; for
i=2:length(array) if isLessWord(...,m) m = ...; pos= i; end
end
function less=isLessWord(wordA,wordB) worda=lower(wordA);
wordb=lower(wordB);
function sortedarray = sortWords(array)
sortedarray = {};
while ~isempty(array)
[m,pos] = findSmallest(array);
array(pos) = [];
sortedarray = [sortedarray m];
end
end
function [m,pos] = findSmallest(array)
m = array{1}; % set m to string at position 1 as the smallest
string
pos = 1; % index of the smallest string position
% loop over the array and find the smallest string in the
array
for i=2:length(array)
if isLessWord(array{i},m)
m = array{i}; % if array at ith position < m , then set m =
string at ith position
pos = i;
end
end
end
function less = isLessWord(wordA,wordB)
% function to return 1 if wordA < wordB else 0
worda = lower(wordA);
wordb = lower(wordB);
less = -1;
if(length(worda) == length(wordb))
word_length = length(worda);
elseif(length(worda) < length(wordb))
word_length = length(worda);
else
word_length = length(wordb);
end
for i=1:word_length
if(worda(i) < wordb(i))
less = 1;
break;
elseif(worda(i) > wordb(i))
less = 0;
break;
end
end
if(less == -1)
if(length(worda) > word_length)
less = 0;
else
less = 1;
end
end
end
% end of script
Output: