w3resource

Scala Programming: Find smallest and second smallest elements of a given array

Scala Programming Array Exercise-27 with Solution

Write a Scala program to find smallest and second smallest elements of a given array.

Sample Solution:

Scala Code:

object Scala_Array {

  def main(args: Array[String]): Unit = {
    val arr = Array(5, 6, -9, 6, 15, 4);
    println("Original array:")
    for (x <- arr) {
      print(s"${x}, ")
    }
    var first_element, second_element, arr_size = arr.length;
    /* Return if the array size less than two */
    if (arr_size < 2) {
      println("\nArray size less than two.");
    } else {
      first_element = Int.MaxValue
      second_element = Int.MaxValue

      for (i <- 0 to arr_size - 1) {
        /* Update both first and second if current element is smaller than first. */
        if (arr(i) < first_element) {
          second_element = first_element;
          first_element = arr(i);
        }

        /* Update second if arr[i] is between first and second
               elements.*/
        else if (arr(i) < second_element && arr(i) != first_element)
          second_element = arr(i);
      }
      if (second_element == Integer.MAX_VALUE)
        println("\nNo second smallest element.");
      else
        println(
          s"\nThe smallest element is ${first_element} and second Smallest  element is ${second_element}."
        );
    }
  }
}

Sample Output:

Original array:
5, 6, -9, 6, 15, 4, 
The smallest element is -9 and second Smallest  element is 4.

Scala Code Editor :

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Scala program to remove the duplicate elements of a given sorted array and return the new length of the array.
Next: Write a Scala program to segregate all 0s on left side and all 1s on right side of a given array of 0s and 1s.

What is the difficulty level of this exercise?



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://w3resource.com/scala-exercises/array/scala-array-exercise-27.php