1 (* Copyright (C
) 2009,2017 Matthew Fluet
.
2 * Copyright (C
) 1999-2006 Henry Cejtin
, Matthew Fluet
, Suresh
3 * Jagannathan
, and Stephen Weeks
.
5 * MLton is released under a BSD
-style license
.
6 * See the file MLton
-LICENSE for details
.
9 structure QuickSort
: QUICK_SORT
=
14 val rand
= Word.toIntX
o Random
.word
16 fun randInt (lo
, hi
) = lo
+ Int.mod (rand(), hi
- lo
+ 1)
18 (* quicksort based on section
10.2 of Programming Pearls
, by Bentley
.
19 * It does repeated partitioning until the segment size is less than the cutoff
.
20 * Then
, it does an insertion sort over the whole array to fix up the unsorted
23 fun 'a
sortArray (a
: 'a array
, op <= : 'a
* 'a
-> bool): unit
=
32 val () = update (a
, i
, x j
)
33 val () = update (a
, j
, t
)
38 fun qsort (l
: int, u
: int): unit
=
39 if Int.<= (u
- l
, cutoff
)
43 val () = swap (l
, randInt (l
, u
))
45 (* Partition based on page
115. *)
52 (* The sentinel guarantees that x i is OK
. *)
70 else (swap (i
, j
); loop (i
, j
))
72 val (i
, j
) = loop (l
, u
+ 1)
74 val () = qsort (l
, j
- 1)
79 (* Put a maximal element at the
end to use
as a sentinel
. *)
82 (a
, (0, Array
.sub (a
, 0)), fn (i
, xi
, (m
, xm
)) =>
86 val last
= length a
- 1
87 val () = swap (m
, last
)
88 val () = qsort (0, last
- 1)
89 val () = InsertionSort
.sort (a
, op <=)
95 fun make (from
, to
) (l
, f
) =
98 val () = sortArray (a
, f
)
103 val sortList
= fn z
=> make (Array
.fromList
, Array
.toList
) z
104 val sortVector
= fn z
=> make (Array
.fromVector
, Array
.toVector
) z