I am trying to make a new sorting method in smalltalk. Anyone know how to change this sorting java code to squeak?
public static void SelectionSort ( int [ ] num )
{
int i, j, first, temp;
for ( i = num.length - 1; i > 0; i - - )
{
first = 0; //initialize to subscript of first element
for(j = 1; j <= i; j ++) //locate smallest element between positions 1 and i.
{
if( num[j] < num[first] )
first = j;
}
temp = num[first]; //swap smallest found with element in position i.
num[first] = num[ i ];
num[i] = temp;
}
}
Here is a line by line translation. Row numbers are not part of the code.
1. selectionSort: num
2. | first temp |
3. num size to: 1 by: -1 do: [:i |
4. first := 1. "initialize to subscript of first element"
5. 1 to: i do: [:j |
6. "locate smallest element between positions 1 and i"
7. (num at: j) < (num at: first) ifTrue: [first := j]].
8. temp := num at: first. "swap smallest with element in position i"
9. num at: first put: (num at: i).
10. num at: i put: temp]
Remarks:
i
and j
declared inside blocks (lines 3 and 5). In Smalltalk, indexed collections are 1 based.num.length()
-> num size
. Decreasing for
loop translates into to:by:do:
message.=
becomes :=
and 0
becomes 1
(see line remark 2 above.)for
loop translates into to:do:
message.[j]
translates into the at: j
message. if
translates into an ifTrue:
message.temp
could have been declared in the first block: do: [:i | | temp |...
.num[j] = temp
also becomes a message sending at:put:
.Idem 9. Note also that you could have used the cascade syntax for lines 9 and 10:
num
at: first put: (num at: i);
at: i put: temp
No need to answer num
because it's been modified by the method. See, however, the interesting discussion originated in Amos' answer: Why shouldn't I store into literal arrays in Smalltalk?.