Move all negative elements to end in scala

Scala program for Move all negative elements to end. Here mentioned other language solution.

// Scala program for
// Move all negative elements at the end of array
class MyArray()
{
	// Display array elements
	def display(arr: Array[Int], n: Int): Unit = {
		var i: Int = 0;
		while (i < n)
		{
			print("  " + arr(i));
			i += 1;
		}
		println();
	}
	// Swap the given array elements
	def swap(arr: Array[Int], start: Int, end: Int): Unit = {
		var temp: Int = arr(start);
		arr(start) = arr(end);
		arr(end) = temp;
	}
	// Method which is move negative elements
	def moveNegative(arr: Array[Int], n: Int): Unit = {
		// first index
		var i: Int = 0;
		// last index
		var j: Int = n - 1;
		while (i < j)
		{
			if (arr(i) < 0 && arr(j) >= 0)
			{
				// When [i] index are have negative value 
				// And [j] is positive then swapping elements values
				swap(arr, i, j);
				// Modified index
				i += 1;
				j -= 1;
			}
			else if (arr(i) >= 0)
			{
				// When element of [i] is not negative
				i += 1;
			}
			else
			{
				j -= 1;
			}
		}
	}
}
object Main
{
	def main(args: Array[String]): Unit = {
		var task: MyArray = new MyArray();
		// Array which are containing positive and negative values
		var arr: Array[Int] = Array(1, -1, 3, 2, -7, -5, 11, 6);
		var n: Int = arr.length;
		println("Before Arrange : ");
		// Before move element
		task.display(arr, n);
		// Move negative elements
		task.moveNegative(arr, n);
		// After arrange
		println("After Arrange : ");
		// After move element
		task.display(arr, n);
	}
}

Output

Before Arrange :
  1  -1  3  2  -7  -5  11  6
After Arrange :
  1  6  3  2  11  -5  -7  -1



Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2022, kalkicode.com, All rights reserved