apl: quicksort recursive partition — Phase 6 classics complete (+9 tests, 315/315)
Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 1m0s

This commit is contained in:
2026-05-07 06:23:03 +00:00
parent e37167a58e
commit 0f13052900
6 changed files with 98 additions and 7 deletions

View File

@@ -257,3 +257,50 @@
(apl-test "permutations of 3 has 6" (len (apl-permutations 3)) 6)
(apl-test "permutations of 4 has 24" (len (apl-permutations 4)) 24)
(apl-test
"quicksort empty"
(mkrv (apl-quicksort (make-array (list 0) (list))))
(list))
(apl-test
"quicksort single"
(mkrv (apl-quicksort (make-array (list 1) (list 42))))
(list 42))
(apl-test
"quicksort already sorted"
(mkrv (apl-quicksort (make-array (list 5) (list 1 2 3 4 5))))
(list 1 2 3 4 5))
(apl-test
"quicksort reverse sorted"
(mkrv (apl-quicksort (make-array (list 5) (list 5 4 3 2 1))))
(list 1 2 3 4 5))
(apl-test
"quicksort with duplicates"
(mkrv (apl-quicksort (make-array (list 7) (list 3 1 4 1 5 9 2))))
(list 1 1 2 3 4 5 9))
(apl-test
"quicksort all equal"
(mkrv (apl-quicksort (make-array (list 5) (list 7 7 7 7 7))))
(list 7 7 7 7 7))
(apl-test
"quicksort negatives"
(mkrv (apl-quicksort (make-array (list 5) (list -3 1 -1 2 0))))
(list -3 -1 0 1 2))
(apl-test
"quicksort 11-element pi"
(mkrv
(apl-quicksort (make-array (list 11) (list 3 1 4 1 5 9 2 6 5 3 5))))
(list 1 1 2 3 3 4 5 5 5 6 9))
(apl-test
"quicksort preserves length"
(first
(mksh (apl-quicksort (make-array (list 7) (list 3 1 4 1 5 9 2)))))
7)

View File

@@ -0,0 +1,25 @@
⍝ Quicksort — the classic Roger Hui one-liner
⍝ Q ← {1≥≢⍵:⍵ ⋄ (∇⍵⌿⍨⍵<p),(p=⍵)/⍵,∇⍵⌿⍨⍵>p←⍵⌷⍨?≢⍵}
⍝ Read right-to-left:
⍝ ?≢⍵ : pick a random index in 1..length
⍝ ⍵⌷⍨… : take that element as pivot p
⍝ ⍵>p : boolean — elements greater than pivot
⍝ ∇⍵⌿⍨… : recursively sort the > partition
⍝ (p=⍵)/⍵ : keep elements equal to pivot
⍝ ⍵<p : boolean — elements less than pivot
⍝ ∇⍵⌿⍨… : recursively sort the < partition
⍝ , : catenate ⟨less⟩ ⟨equal⟩ ⟨greater⟩
⍝ 1≥≢⍵:⍵ : guard — base case for length ≤ 1
⍝ Stability: not stable on duplicates (but eq-class is preserved as a block).
⍝ Worst case O(N²) on already-sorted input with deterministic pivot;
⍝ randomized pivot selection gives expected O(N log N).
⍝ Examples:
⍝ Q 3 1 4 1 5 9 2 6 5 3 5 → 1 1 2 3 3 4 5 5 5 6 9
⍝ Q 0 → ⍬ (empty)
⍝ Q ,42 → 42
quicksort {1: p? (<p),(p=)/,>p}