Groovy 34- Algorithm to extract the smallest integer from an Array
Find the Smallest Integer in an Array
Given the following array:
int[] myArray = [33, 54, 78, 996, 4332, 454, 6, 7676, 2, 123, 6, 90, 12, 3213, 6789, 54];
We want to find the smallest integer using the Comparison Sort Algorithm.
Comparison Sort is a type of sorting algorithm that only reads the list elements through a single comparison operation. This operation determines which of two elements should come first in the final sorted list.
The requirements for the operator are:
- If a ≤ b and b ≤ c, then a ≤ c (transitivity).
- For all a and b, either a ≤ b or b ≤ a (totality).
The Groovy code to find the smallest integer in the array is:
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];