Some checks failed
Test, Build, and Deploy / test-build-deploy (push) Failing after 1m0s
26 lines
1.2 KiB
APL
26 lines
1.2 KiB
APL
⍝ 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}
|