Move all negative elements to end in typescript

Ts program for Move all negative elements to end. Here more solutions.

// TypeScript program for
// Move all negative elements at the end of array
class MyArray
{
	// Display array elements
	public display(arr: number[])
	{
		console.log(arr);
		console.log();
	}
	// Swap the given array elements
	public swap(arr: number[], start: number, end: number)
	{
		var temp = arr[start];
		arr[start] = arr[end];
		arr[end] = temp;
	}
	// Method which is move negative elements
	public moveNegative(arr: number[], n: number)
	{
		// first index
		var i = 0;
		// last index
		var j = 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
				this.swap(arr, i, j);
				// Modified index
				i++;
				j--;
			}
			else if (arr[i] >= 0)
			{
				// When element of [i] is not negative
				i++;
			}
			else
			{
				j--;
			}
		}
	}
	public static main(args: string[])
	{
		var task = new MyArray();
		// Array which are containing positive and negative values
		var arr: number[] = [1, -1, 3, 2, -7, -5, 11, 6];
		var n = arr.length;
		console.log("Before Arrange : ");
		// Before move element
		task.display(arr);
		// Move negative elements
		task.moveNegative(arr, n);
		// After arrange
		console.log("After Arrange : ");
		// After move element
		task.display(arr);
	}
}
MyArray.main();
/*
 file : code.ts
 tsc --target es6 code.ts
 node code.js
 */

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







Vadim     143 Day ago
How about this?

1, 2, -1, 3].sort((a, b) => b < 0 ? -1 : 0)
// [1, 2, 3, -1]

© 2022, kalkicode.com, All rights reserved