Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS

confused by this function i found

Would anyone be able to explain to me how this function returns the largest and smallest elements in the array?

func largestAndSmallest(inArray:[Int])-> (Int, Int) {
   var largest = inArray[0]
    var smallest = inArray[0]
    for index in 1..<inArray.count {
        if largest < inArray[index] {
            largest = inArray[index]
        }
        if smallest > inArray[index] {
            smallest = inArray[index]
      }

    }
    return (largest, smallest)
}

i cant really understand the if statements with largest being "less than" and smallest being "greater than"? i am a bit disappointed in myself for not understanding these basics, but i figured id ask for help. thank you

An example would help you understand this really quickly:

Example array: [3, 4, 5, 1]

At first:

largest = 3 smallest = 3

1st iteration:

inArray[1] = 4

if 3 < 4 which is true, largest now = 4 if 3 > 4 which is false, smallest remains 3

2nd iteration:

inArray[2] = 5

if 4 < 5 which is true, largest now = 5 if 3 > 5 which is false, smallest remains 3

last iteration:

inArray[3] = 1

if 5 < 1 which is false, largest remains 5 if 3 > 1 which is true, smallest now = 1

Eyeballing the array would quickly tell us that 1 is indeed the smallest and 5 is indeed the biggest.

In essence, the function assumes that the first element is both the largest and smallest and iterates over every single element in the Array, check whether the current smallest/largest is indeed smaller or larger than the current iterable element and updating the largest and smallest.

At the end of every single element, the function will correctly return the smallest and the largest element from the element.

1 Answer

thank you Jun Hao, totally understand what is going on now. Much appreciated for the detailed explanation!