w3resource

Scala Programming: Rearrange a given array of unique elements such that every second element of the array is greater than its left and right elements

Scala Programming Array Exercise-37 with Solution

Write a Scala program to rearrange a given array of unique elements such that every second element of the array is greater than its left and right elements.

Example:
Input:
nums= { 1, 2, 4, 9, 5, 3, 8, 7, 10, 12, 14 }
Output:
Array with every second element is greater than its left and right elements:
[1, 4, 2, 9, 3, 8, 5, 10, 7, 14, 12]

Sample Solution:

Scala Code:

object Scala_Array {

  def rearrange_Array_nums(nums: Array[Int]): Array[Int] = {
    var t_nums = 0;
    for (i <- 1 to nums.length - 1 by 2) {
      if (nums(i - 1) > nums(i)) {
        t_nums = nums(i - 1);
        nums(i - 1) = nums(i);
        nums(i) = t_nums;
      }

      if (i + 1 < nums.length && nums(i + 1) > nums(i)) {
        t_nums = nums(i + 1);
        nums(i + 1) = nums(i);
        nums(i) = t_nums;
      }
    }
    nums;
  }

  def main(args: Array[String]): Unit = {
    val nums = Array(1, 2, 4, 9, 5, 3, 8, 7, 10, 12, 14);
    println("Original array:")
    for (x <- nums) {
      print(s"${x}, ")
    }
    val result = rearrange_Array_nums(nums)
    println(
      "\nArray with every second element is greater than its left and right elements:"
    )
    for (x <- result) {
      print(s"${x}, ")
    }
  }
}

Sample Output:

Original array:
1, 2, 4, 9, 5, 3, 8, 7, 10, 12, 14, 
Array with every second element is greater than its left and right elements:
1, 4, 2, 9, 3, 8, 5, 10, 7, 14, 12,

Scala Code Editor :

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

Previous: Write a Scala program to find maximum product of two integers in a given array of integers.
Next: Write a Scala program to find maximum difference between two elements in a given array of integers such that smaller element appears before larger element.

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://www.w3resource.com/scala-exercises/array/scala-array-exercise-37.php