Sorting Algorithm

Christopher Roach chrisroach at btinternet.com
Fri Nov 16 18:12:37 UTC 2001


	|s c n r|
	"get the ASCII NUL character to use as field separator"
	n := Character value: 0.
	"open the source file"
	s := StandardFileStream oldFileNamed: 'data.raw'.
	"create an empty collection"
	c := OrderedCollection new.
	[s atEnd] whileFalse: [
	    "read a record as a string without the line terminator"
	    r := s nextLine.
	    "replace commas by NULs"
	    r replaceAll: $, with: n.
	    "add the transformed record to the collection"
	    c add: r].
	"sort the collection using <= for comparison"
	c := c asSortedCollection.
	"open the destination file"
	s := StandardFileStream newFileNamed: 'data.ord'.
	"write out each element of the sorted collection"
	c do: [:t |
	    "t is a transformed record.  Undo the transformation"
	    t replaceAll: n with: $,.
	    "write the reconstructed record to the output stream"
	    s nextPutAll: t; cr].
	"close the output stream"
	s close.


Thanks Richard for the above code, I understand that you have not 
tested it yet.

I am just thinking here... will smalltalk do a comparison on each 
letter at a time?  so lets say we have:

aaaa
compared to:
aaab  does smalltalk go through first a's and compare it, then move 
onto second a, compare that, until it gets to the fourth THEN it 
realizes that they are different and moves on?  

The code that Bert gave:

order := [:a :b | 
  a title < b title or: [
    a title = b title and: [a name < b name or: [
      a name = b name and: [a ref < b ref or: [
        a number < b number]]]]]]

Does this in effect just get the first two characters of the field 
and do a comparison?  yeah?  the words "title" and "name" and all 
that in this method - does that make a difference?  how does 
smalltalk regard that? could it just be:

order := [:a :b | 
  a  < b  or: [
    a  = b  and: [a  < b  or: [
      a  = b  and: [a  < b  or: [
        a  < b ]]]]]]


Can you produce a record in smalltalk like in C++, so it could be 
something like:

Struct
{
char[] name,
char [] title,
char [] ref,
int number
}












More information about the Squeak-dev mailing list