Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting int array with only 3 elements

I have this array:

int [] myarray =  {17, 6, 8};

What is the optimal way to sort this array, in pseudocode?

Thanks!

like image 410
clamp Avatar asked Jan 25 '11 12:01

clamp


People also ask

How do you sort a partial array?

Arrays. sort() method can be used to sort a subset of the array elements in Java. This method has three arguments i.e. the array to be sorted, the index of the first element of the subset (included in the sorted elements) and the index of the last element of the subset (excluded from the sorted elements).

How do I sort an array from a specific index?

To sort an array only in specified index range, you can call Arrays. sort() method and pass the arguments: array, starting-index and to-index to the method. arr is the array of elements. The array could be of type byte, char, double, integer, float, short, long, object, etc.

How do you sort an array in a specific order?

Sorting an array of objects in javascript is simple enough using the default sort() function for all arrays: const arr = [ { name: "Nina" }, { name: "Andre" }, { name: "Graham" } ]; const sortedArr = arr.


2 Answers

I think this should be quite fast (ascending order):

if (el1 > el2) Swap(el1,el2)
if (el2 > el3) Swap(el2,el3)
if (el1 > el2) Swap(el1,el2)
like image 70
nan Avatar answered Oct 04 '22 00:10

nan


May this graphic showing a decision tree for sorting three elements helps: enter image description here

like image 30
Michael Dorner Avatar answered Oct 04 '22 01:10

Michael Dorner