Skip to content

Commit

Permalink
QuickSort example
Browse files Browse the repository at this point in the history
  • Loading branch information
Edd12321 committed Jun 19, 2023
1 parent daf14cc commit f395fd7
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions examples/quicksort.zrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#!../bin/zrc
%include list

fn quicksort {
let {m pivot less equal greater vn x} {
set m = $argv(1)
# Bail out if only one elem in list
if {[llength $m] <= 1} {
return $m
}

set pivot = [lindex $m 0]
set less = [set equal := [set greater := [list]]]

# Iterate through list
foreach x {*}$m {
set x = [subst $x]
echo 'x=$x, pivot=$pivot'

# See what var to dereference
# (leq, eq or geq)
switch [expr {$x <=> $pivot}] {
case -1 { set vn = 'less' }
case 0 { set vn = 'equal' }
case 1 { set vn = 'greater' }
}
set $vn = '$$vn $x'
}
return "
[quicksort $less]
$equal
[quicksort $greater]"
}
}

set L = {8 6 4 2 1 3 5 7 9}

# Main routine
fn main {
set L = [quicksort $L]
foreach x {*}$L {
echo -n [subst $x] ' '
}
echo
return 0
}; main

0 comments on commit f395fd7

Please sign in to comment.