Short answer:
You don't have to.
To sort an array, just send it the message #asSortedCollection
. For instance, inspect this in a workspace:
#(7 2 8 5) asSortedCollection
Long answer:
Since I assume you want to see how you would implement the equivalent of your Java code in Smalltalk if you really had to, here's a relatively "literal translation" you can test in a workspace (tested in Pharo, should work in Squeak as well):
| someNumbers |
someNumbers := #(7 2 8 5) copy. "See comments below for an explanation."
someNumbers size to: 1 by: -1 do: [:eachOuterIndex |
| indexOfSmallest swapValue |
indexOfSmallest := 1.
1 to: eachOuterIndex do: [:eachInnerIndex |
(someNumbers at: eachInnerIndex) < (someNumbers at: indexOfSmallest)
ifTrue: [ indexOfSmallest := eachInnerIndex ]
].
swapValue := someNumbers at: indexOfSmallest.
someNumbers at: indexOfSmallest put: (someNumbers at: eachOuterIndex).
someNumbers at: eachOuterIndex put: swapValue.
].
^someNumbers
Clearly, there are a few changes from your version, such as using explicit naming, which is one of Smalltalk's hallmark conventions (in particular, indexOfSmallest
should be clearer than first
, which is misleading since it's not necessarily the first index), and decreasing the scope of the variables you called first
and temp
). See @Leandro's answer for a version that uses your own variable names if you have trouble with the "translation".
If the code were to live in a method, I would probably put it in the SequenceableCollection
hierarchy (or maybe you'd want to add yours as a subclass in there if you want to override other behaviour), and the start of it could look something like this:
copySortedDescending
"Answer a copy of the receiver, sorted in descending order."
| copy |
copy := self copy.
copy size to: 1 by: -1 do: [:eachOuterIndex |
"... and so on..."
].
^copy
Again, note that I'm deliberately changing the name, because I don't think selectionSort
is a descriptive name of what the method does, and I wouldn't use a collection as an argument to a method living somewhere else - the knowledge of how to do the sorting belongs on the collection itself.
I'm sure you could come up with a better roll-your-own-answer very easily, though. For instance, you could try sending a SequenceableCollection
instance the message sort:
and pass a sort block as an argument, in which you could specify how you want your elements to be sorted.