Sorting algorithms/Merge sort: Difference between revisions

m
→‎{{header|Standard ML}}: minor reformat of SML and extra example
(→‎{{header|Component Pascal}}: Modified to show that the sort is stable)
m (→‎{{header|Standard ML}}: minor reformat of SML and extra example)
 
(3 intermediate revisions by 2 users not shown)
Line 2,937:
RETURN t.TakeSort(n, s) (* Return the sorted list *)
END Sort;
 
END RosettaMergeSort.
</syntaxhighlight>
Interface extracted from implementation:
<syntaxhighlight lang="oberon2">
DEFINITION RosettaMergeSort;
 
TYPE
Template = ABSTRACT RECORD
(IN t: Template) Before- (front, rear: ANYPTR): BOOLEAN, NEW, ABSTRACT;
(IN t: Template) Next- (s: ANYPTR): ANYPTR, NEW, ABSTRACT;
(IN t: Template) Set- (s, next: ANYPTR): ANYPTR, NEW, ABSTRACT;
(IN t: Template) Sort (s: ANYPTR): ANYPTR, NEW
END;
 
END RosettaMergeSort.
Line 2,971 ⟶ 2,985:
BEGIN
IF next = NIL THEN s(List).next := NIL
ELSE s(List).next := next(List) END;
RETURN s
END Set;
Line 4,577 ⟶ 4,591:
 
=={{header|Julia}}==
{{works with|Julia|0.6}}
 
<syntaxhighlight lang="julia">function mergesort(arr::Vector)
if length(arr) ≤ 1 return arr end
Line 4,597 ⟶ 4,609:
end
if li ≤ length(lpart)
copycopyto!(rst, i, lpart, li)
else
copycopyto!(rst, i, rpart, ri)
end
return rst
Line 7,403 ⟶ 7,415:
| merge cmp (xs, []) = xs
| merge cmp (xs as x::xs', ys as y::ys') =
case cmp (x, y) of GREATER => y :: merge cmp (xs, ys')
| _ GREATER => xy :: merge cmp (xs', ys')
| _ => x :: merge cmp (xs', ys)
;
 
fun merge_sort cmp [] = []
| merge_sort cmp [x] = [x]
Line 7,413 ⟶ 7,426:
in
merge cmp (merge_sort cmp ys, merge_sort cmp zs)
end</syntaxhighlight>
{{out|Poly/ML}}
;
<pre>
> merge_sort Int.compare [8,6,4,2,1,3,5,7,9]</syntaxhighlight>;
val it = [1, 2, 3, 4, 5, 6, 7, 8, 9]: int list
> merge_sort String.compare ["Plum", "Pear", "Peach", "Each"];
val it = ["Each", "Peach", "Pear", "Plum"]: string list
>
</syntaxhighlight>
 
=={{header|Swift}}==
23

edits