smalltalk: quicksort classic program + 9 tests
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Has been cancelled
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Has been cancelled
This commit is contained in:
31
lib/smalltalk/tests/programs/quicksort.st
Normal file
31
lib/smalltalk/tests/programs/quicksort.st
Normal file
@@ -0,0 +1,31 @@
|
||||
"Quicksort — Lomuto partition. Sorts an Array in place. Classic-corpus
|
||||
program for the Smalltalk-on-SX runtime."
|
||||
|
||||
Object subclass: #Quicksort
|
||||
instanceVariableNames: ''!
|
||||
|
||||
!Quicksort methodsFor: 'sort'!
|
||||
sort: arr ^ self sort: arr from: 1 to: arr size!
|
||||
|
||||
sort: arr from: low to: high
|
||||
| p |
|
||||
low < high ifTrue: [
|
||||
p := self partition: arr from: low to: high.
|
||||
self sort: arr from: low to: p - 1.
|
||||
self sort: arr from: p + 1 to: high].
|
||||
^ arr!
|
||||
|
||||
partition: arr from: low to: high
|
||||
| pivot i tmp |
|
||||
pivot := arr at: high.
|
||||
i := low - 1.
|
||||
low to: high - 1 do: [:j |
|
||||
(arr at: j) <= pivot ifTrue: [
|
||||
i := i + 1.
|
||||
tmp := arr at: i.
|
||||
arr at: i put: (arr at: j).
|
||||
arr at: j put: tmp]].
|
||||
tmp := arr at: i + 1.
|
||||
arr at: i + 1 put: (arr at: high).
|
||||
arr at: high put: tmp.
|
||||
^ i + 1! !
|
||||
Reference in New Issue
Block a user