%mathpiper,def="SmallSort"

/// fast in-place sorting of a list (or array!)
/// SmallSort sorts up to 3 elements, HeapSort sorts 4 and more elements
SmallSort(_list, _first, _last, _compare) _ (last=first) <-- list;
SmallSort(_list, _first, _last, _compare) _ (last=first+1) <--
[
	Local(temp);
	temp := list[first];
	If(
		Apply(compare,{temp,list[last]}),
		list,
		[
			list[first] := list[last];
			list[last] := temp;
		]	//Swap(list, first, last)
	);
	list;
];
SmallSort(_list, _first, _last, _compare) _ (last=first+2) <--
[
	Local(temp);
	temp := list[first];
	If(
		Apply(compare,{list[first+1],temp}),
		[
			list[first] := list[first+1];
			list[first+1] := temp;
		]	//Swap(list, first, first+1)	// x>y, z
	);
	// x<y, z
	temp := list[last];
	If(
		Apply(compare,{list[first],temp}),
		If(	// z>x<y
			Apply(compare,{list[first+1],temp}),
			list,
			[
				list[last] := list[first+1];
				list[first+1] := temp;
			]	//Swap(list, first+1, last)	// 1, 3, 2
		),
		[	// 2, 3, 1 -> 1, 2, 3
			list[last] := list[first+1];
			list[first+1] := list[first];
			list[first] := temp;
		]
	);
	list;
];

%/mathpiper