w3resource

Scala Programming: Arrange the elements of a given array of integers where all negative integers appear before all the positive integers

Scala Programming Array Exercise-32 with Solution

Write a Java program to arrange the elements of a given array of integers where all positive integers appear before all the negative integers.

Sample Solution:

Scala Code:

object Scala_Array {
  def main(args: Array[String]): Unit = {
    val arra_nums = Array(-4, 8, 6, -5, 6, -2, 1, 2, 3, -11);
    println("Original array:");
    for (x <- arra_nums) {
      print(s"${x}, ")
    }
    var j, temp = 0;

    val arr_size = arra_nums.length;
    for (i <- 0 to arr_size - 1) {
      j = i;
      //Shift positive numbers left, negative numbers right
      while ((j > 0) && (arra_nums(j) > 0) && (arra_nums(j - 1) < 0)) {
        temp = arra_nums(j);
        arra_nums(j) = arra_nums(j - 1);
        arra_nums(j - 1) = temp;
        j = j - 1;
      }
    }
    println(
      "\nNew array Shifting positive numbers left, negative numbers right:"
    );
    for (x <- arra_nums) {
      print(s"${x}, ")
    }
  }
}

Sample Output:

Original array:
-4, 8, 6, -5, 6, -2, 1, 2, 3, -11, 
New array Shifting positive numbers left, negative numbers right:
8, 6, 6, 1, 2, 3, -4, -5, -2, -11,

Scala Code Editor :

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

Previous: Write a Scala program to count the number of possible triangles from a given unsorted array of positive integers.
Next: Write a Scala program to separate even and odd numbers of a given array of integers. Put all even numbers first, and then odd numbers.

What is the difficulty level of this exercise?