Quickselect algorithm: Difference between revisions

Line 2,086:
=={{header|Mercury}}==
{{works with|Mercury|22.01.1}}
 
 
To more strictly follow the task instructions at the time I am writing this (which call for printing from 1st to 10th ''largest'', in order) I use '''>''' as my ordering predicate. In the generic parts of the code, the predicate is called "Less_than", but '''<''' is simply a conventional name for an ordering predicate. You can read it as meaning "comes before", or "has ordinal less than".
 
However, the sample vector looks as if it were devised to test finding the kth ''least'' element, so I also run the task with '''<''' as the ordering predicate.
 
 
Line 2,266 ⟶ 2,261:
Print_kth_least = (pred(K::in, di, uo) is det -->
print_kth_least(K, example_numbers, M)),
print("With < as order predicate: ", !IO),
foldl(Print_kth_least, 1 `..` 10, !IO),
print_line("", !IO),
print_lineprint("InWith order> fromas greatestorder to leastpredicate: ", !IO),
print_line("", !IO),
print_line(" nth value", !IO),
foldl(Print_kth_greatest, 1 `..` 10, !IO),
print_line("", !IO),
print_line("In order from least to greatest:", !IO),
print_line("", !IO),
print_line(" nth value", !IO),
foldl(Print_kth_least, 1 `..` 10, !IO),
print_line("", !IO).
 
:- pred print_kth_least(int::in, list(int)::in,
M::in, io::di, io::uo)
is det <= urandom(M, io).
print_kth_least(K, Numbers_list, M, !IO) :-
(array.from_list(Numbers_list, Arr0)),
quickselect(<, K - 1, Arr0, _, Elem, M, !IO),
print_lineprint(" ", !IO),
print(Elem, !IO).
 
:- pred print_kth_greatest(int::in, list(int)::in,
Line 2,290 ⟶ 2,289:
quickselect(>, K - 1, Arr0, _, Elem, M, !IO),
 
formatprint(" %2d %d\n", [i(K), i(Elem)], !IO).,
print(Elem, !IO).
 
:- pred print_kth_least(int::in, list(int)::in,
M::in, io::di, io::uo)
is det <= urandom(M, io).
print_kth_least(K, Numbers_list, M, !IO) :-
(array.from_list(Numbers_list, Arr0)),
quickselect(<, K - 1, Arr0, _, Elem, M, !IO),
format(" %2d %d\n", [i(K), i(Elem)], !IO).
 
%%%-------------------------------------------------------------------
Line 2,308 ⟶ 2,301:
{{out}}
<pre>$ mmc quickselect_task.m && ./quickselect_task
With < as order predicate: 0 1 2 3 4 5 6 7 8 9
 
With > as order predicate: 9 8 7 6 5 4 3 2 1 0</pre>
In order from greatest to least:
 
nth value
1 9
2 8
3 7
4 6
5 5
6 4
7 3
8 2
9 1
10 0
 
In order from least to greatest:
 
nth value
1 0
2 1
3 2
4 3
5 4
6 5
7 6
8 7
9 8
10 9
 
</pre>
 
=={{header|NetRexx}}==
1,448

edits