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

  • برمجة سكالا

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

الأجوبة

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.
هل كان المحتوى مفيد؟

معلومات ذات صلة

تبحث عن مدرس اونلاين؟

محتاج مساعدة باختيار المدرس الافضل؟ تواصل مع فريقنا الان لمساعدتك بتأمين افضل مدرس
ماهو التخصص الذي تبحث عنه؟
اكتب هنا...