Can a program be written that can sort a set of words alphabetically?
Afficher commentaires plus anciens
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 commentaire
Geoff Hayes
le 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).
Réponses (2)
Walter Roberson
le 18 Nov 2015
Modifié(e) : Walter Roberson
le 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
le 18 Nov 2015
Is this homework? Otherwise just use sort
words = {'a' 'z' 'foo' 'bar' 'unsorted' 'help'}
sort(words)
Catégories
En savoir plus sur Shifting and Sorting Matrices dans Centre d'aide et File Exchange
Produits
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!