Bubble sort (Smalltalk)

From LiteratePrograms

Jump to: navigation, search
Other implementations: C | CLIPS | C++ | C# | Eiffel | Erlang | Io | Java | Lisp | Smalltalk

Here an implementation of bubble sort algorithm in Smalltalk. This implementation is generic in the comparison function, cmpFun, that it uses for determining the sort order.

<<bubble sort>>=
bubbleSort: cmpFun 
	"Implementing Bubble sort with Smalltalk"
	| i j tmp funResult |
	i := self size.
	[i > 0]
		whileTrue: [j := 1.
			[j <= i]
				whileTrue: [funResult := cmpFun
								value: (self at: i)
								value: (self at: j).
					funResult
						ifTrue: [tmp := self at: i.
							self
								at: i
								put: (self at: j).
							self at: j put: tmp].
					j := j + 1].
			i := i - 1]

One has to start with i := self size because Arrays in Smalltalk are 1-based. So the first element in an Array is at position 1. This is in contrast to languages such as C, in which array indexing is 0-based.

Now in Smalltalk if the size of an Array is three we can access the last element like this arr at: 3

The swapping of elements has been inlined, however generalizing it might be a good idea.

Importing into Squeak

To allow this method to be easily imported into Squeak Smalltalk, we place it in an .st file with the appropriate surrounding markup for importing into the Array class using file-in.

<<bubbleSort.st>>=
!Array methodsFor: 'sorting' stamp:''!
bubble sort! !
Views