Locating the Smallest Entry in an Array
In this lesson, we will search an array for its smallest value and then learn the index at which this value occurs.
We'll cover the following
When the entries in an array can be compared with each other, we can find the smallest (or largest) among them. We either can report the value of that entry or give only its location in the array, that is, its index.
Finding the smallest entry in an array
For example, let’s consider an array data
of numberCount
positive integers. We know that we can compare one integer with another one. Let’s assume that numberCount
does not exceed data.length
, the capacity of the array. Let’s make the additional assumption that numberCount
is greater than zero; that is, we’ll assume that the array contains at least one integer.
Our strategy is to examine each integer in the array and to ask “Is this the smallest value we have seen so far?” The first integer in the array is the smallest so far. If the second integer is larger, we go on to examine the third one. But if the second integer is smaller, it becomes the smallest we have seen so far. We would then compare it with the third integer, and so on. The figure given below illustrates this strategy. An arrow marks the next integer in the array to be considered, while blue shading highlights the smallest integer so far.
Get hands-on with 1400+ tech skills courses.