Can a program be written that can sort a set of words alphabetically?

1 view (last 30 days)
The idea sounds pretty cool and this is what I have so far.
function sorted=sortWords(array)
sorted={};
while ~isempty(array)
[m,pos]=findSmaller(array);
array(pos)=[];
sorted=[sort m];
end
function [m,pos]=findSmallest(array)
m=%Something here
pos=1;
for i=2:length(array)
if isLessWord(%Something here),m
m=%something here
pos=1;
end
end
function less=isLessWord(wordA,wordB)
worda=lower(wordA);
wordb=lower(wordB);
if worda(1)<wordb(1)
less=true;
%This would be the terminating statement for a recursive function but I'm not the best at those
%so I may cut it out and do it the hard way.
end
  1 Comment
Geoff Hayes
Geoff Hayes on 18 Nov 2015
Yes, Patrick, you can write a program to sort a set of words. You may want to clearly outline the algorithm that you are going to implement. For example, you could sort on the first character of each word, and then break that sorted set into subsets where the word in each subset starts with the same character. Then recursively call your sorting algorithm on each subset (less the initial character).

Sign in to comment.

Answers (2)

Walter Roberson
Walter Roberson on 18 Nov 2015
Edited: Walter Roberson on 18 Nov 2015
You have
sorted=[sort m];
you have not defined a variable named "sort", so you are calling the MATLAB routine named sort() there, and passing it no arguments, as if you had written
sorted=[sort() m];
The MATLAB routine named "sort" requires an input argument, so that line is going to generate an error.
You appear to be calling upon a routine named findSmaller(), but you do not define a routine by that name: you define a routine named findSmallest

Thorsten
Thorsten on 18 Nov 2015
Is this homework? Otherwise just use sort
words = {'a' 'z' 'foo' 'bar' 'unsorted' 'help'}
sort(words)

Categories

Find more on Shifting and Sorting Matrices in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!