For example we have the following array:
int[] myArray = [33,54,78,996,4332,454,6,7676,2,123,6,90,12,3213,6789,54];
Now the algorithm to extract the smallest integer from this array is called Comparison sort Algorithm
Wiky:
A comparison sort is a type of sorting algorithm that only reads the list elements through a single abstract comparison operation (often a “less than or equal to” operator or a three-way comparison) that determines which of two elements should occur first in the final sorted list. The only requirement is that the operator obey two of the properties of a total order:
- if a ≤ b and b ≤ c then a ≤ c (transitivity)
- for all a and b, either a ≤ b or b ≤ a (totalness or trichotomy).
It is possible that both a ≤ b and b ≤ a; in this case either may come first in the sorted list. In a stable sort, the input order determines the sorted order in this case.
In groovy code looks like this:
int min = myArray[0];
int index = 0;
for(int i = 0 ;i< myArray.size();i++){
if(myArray[i]<min){
min = myArray[i];
index = i;
}
}
return myArray[index]