-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquicksort.wat
More file actions
98 lines (77 loc) · 2.12 KB
/
quicksort.wat
File metadata and controls
98 lines (77 loc) · 2.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
(module
(memory (export "memory") 1)
(func $partition (param $lo i32) (param $hi i32) (param $pivot i32) (result i32)
(local $tmp i32)
(if
(i32.gt_u (i32.add (get_local $lo) (i32.const 4)) (get_local $hi))
(return (get_local $hi))
)
(loop $forever
;; increase lower bound
(loop $while1
(if
(i32.lt_s (i32.load (get_local $lo)) (get_local $pivot))
(then
(set_local $lo (i32.add (get_local $lo) (i32.const 4)))
(br $while1)
)))
;; increase upper bound
(loop $while2
(if
(i32.gt_s (i32.load (get_local $hi)) (get_local $pivot))
(then
(set_local $hi (i32.sub (get_local $hi) (i32.const 4)))
(br $while2)
)))
;; return if we are sorted
(if
(i32.ge_u (get_local $lo) (get_local $hi))
(return (get_local $hi))
)
;; swap hi and lo
(set_local $tmp (i32.load (get_local $hi)))
(i32.store (get_local $hi) (i32.load (get_local $lo)) )
(i32.store (get_local $lo) (get_local $tmp) )
(set_local $hi (i32.sub (get_local $hi) (i32.const 4)))
(br $forever)
)
(get_local $hi)
)
(func $sort (param $lo i32) (param $hi i32) (result i32)
(local $mid i32)
(if
(i32.ge_s (get_local $lo) (get_local $hi))
(return (get_local $hi))
)
;; make sure mid is alligned to the same bytes that hi and lo are.
;; probably would be faster to use bitshift
(set_local $mid
(i32.mul
(i32.div_s
(i32.div_s
(i32.add (get_local $lo) (get_local $hi))
(i32.const 4))
(i32.const 2)
)
(i32.const 4))
)
(set_local $mid (call $partition
(get_local $lo)
(get_local $hi)
(i32.load (get_local $mid))
))
(call $sort
(get_local $lo)
(i32.sub (get_local $mid) (i32.const 4))
)
(drop)
(call $sort
(i32.add (get_local $mid) (i32.const 4))
(get_local $hi)
)
(drop)
(get_local $mid)
)
(export "partition" (func $partition))
(export "sort" (func $sort))
)