Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort three variables using at most two swaps?

Tags:

The following algorithm can sort three variables x, y and z of type K which are comparable using operator<:

void sort2(K& x, K& y) {    if(y < x)       swap(x, y); }        void sort3(K& x, K& y, K& z) {    sort2(x, y);    sort2(y, z);    sort2(x, y); } 

This needs three swaps in the "worst case". However basic mathematics tells us, that the ordering of three values can be done using only two swaps.

Example: The values (c,b,a) will be sorted using three swaps: (c,b,a) -> (b,c,a) -> (b,a,c) -> (a,b,c). However one swap would have been enough: (c,b,a) -> (a,b,c).

What would be the simplest algorithms which sorts three variables with at most two swaps in all cases?

like image 240
Danvil Avatar asked Jul 27 '10 12:07

Danvil


People also ask

Which sorting algorithm uses maximum number of swaps?

Insertion sort – Worst Case input for maximum number of swaps will be already sorted array in ascending order. When a new element is inserted into an already sorted array of k size, it can lead to k swaps (in case it is the smallest of all) in worst case.

How do you swap three variables?

To swap three numbers, first, we initialize three variables i.e. first_number, second_number, and third_number. With these three numbers, a temporary variable named temp is also initialized to store a number temporarily. Then scan allows the user to assigned numbers according to their wish.

Which sorting algorithm is best for swapping?

Insertion Sort is suitable for arrays of small size. It also achieves best-case complexity of O(n) if the arrays are already sorted.

How do you swap three variables without using a third variable?

Method 1 (Using Arithmetic Operators) The idea is to get sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from sum.


1 Answers

Find the smallest, this takes 2 comparisons, and swap it into the first position. Then compare the remaining 2 and swap if necessary.

if (x < y) {    if (z < x) swap(x,z); } else {   if (y < z) swap(x,y);   else swap(x,z); }  if(z<y) swap(y,z); 

This takes 3 comparisons, but only two swaps.

like image 68
deinst Avatar answered Oct 21 '22 08:10

deinst