How to make a sorting method in smalltalk

I am trying to create a new sorting method in smalltalk. Does anyone know how to change this java sort 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; 
      }           
}
+4
source share
2 answers

Here is line feed line by line. Line 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]

Notes:

  • An argument type declaration. No answer.
  • Lock temporary files iand jdeclared inside blocks (lines 3 and 5). In Smalltalk, indexed collections are based on 1.
  • num.length()num size. Decrease the loop is forconverted to a message to:by:do:.
  • = := 0 1 (. 2 ).
  • for to:do:.
  • .
  • [j] at: j. if ifTrue:.
  • temp : do: [:i | | temp |....
  • num[j] = temp at:put:.
  • 9. , 9 10:

    num
        at: first put: (num at: i);
        at: i put: temp
    
  • num, . ., , : Smalltalk?.

+6

:

.

, #asSortedCollection. , :

#(7 2 8 5) asSortedCollection

:

, , Java- Smalltalk, , " ", ( Pharo, Squeak ):

| 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

, , , Hallmark ( , indexOfSmallest , first), , ) , first temp). . @Leandro , , "".

, , , SequenceableCollection (, , , ), :

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

, , , , selectionSort , , , else - , , .

, "roll-your-own-answer" . , SequenceableCollection sort: , , , .

+7

All Articles