Search code examples
sortingmethodssmalltalksqueak

how to make a sorting method in smalltalk


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; 
      }           
}

Solution

  • 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:

    1. No argument type declaration. No answer type.
    2. Block temporaries i and j declared inside blocks (lines 3 and 5). In Smalltalk, indexed collections are 1 based.
    3. num.length() -> num size. Decreasing for loop translates into to:by:do: message.
    4. Assignment = becomes := and 0 becomes 1 (see line remark 2 above.)
    5. Increasing for loop translates into to:do: message.
    6. Comments are enclosed between double quotes.
    7. [j] translates into the at: j message. if translates into an ifTrue: message.
    8. temp could have been declared in the first block: do: [:i | | temp |....
    9. num[j] = temp also becomes a message sending at:put:.
    10. 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
      
    11. 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?.