Posted on by Kalkicode
Code Recursion

Reverse array using recursion in node js

Js program for Reverse array using recursion. Here more information.

// Node JS program for
// Reverse array using recursion
class Transformation
{
	// print array elements
	display(data, size)
	{
		// Loop which is iterating array elements
		for (var i = 0; i < size; ++i)
		{
			process.stdout.write("  " + data[i]);
		}
		process.stdout.write("\n");
	}
	// This is reversing the array elements of given array
	reverseArray(data, front, tail)
	{
		if (front < tail)
		{
			// Swap the array elements
			var auxiliary = data[front];
			data[front] = data[tail];
			data[tail] = auxiliary;
			// Recursive execute
			this.reverseArray(data, front + 1, tail - 1);
		}
	}
}

function main()
{
	var task = new Transformation();
	// Define array of integer elements
	var data = [1, 2, 7, 3, 4, 5, 8, 9];
	// Get the size of array
	var size = data.length;
	console.log(" Before Reverse ");
	task.display(data, size);
	task.reverseArray(data, 0, size - 1);
	console.log(" After Reverse ");
	task.display(data, size);
}
// Start program execution
main();

Output

 Before Reverse
  1  2  7  3  4  5  8  9
 After Reverse
  9  8  5  4  3  7  2  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