JavaScript Progam to rearrange an array in maximum minimum form using Two Pointer Technique
Last Updated :
26 Aug, 2024
In this article, we are going to learn about rearranging an array in maximum minimum form using the Pointer Technique in JavaScript. Rearranging an array in maximum-minimum form with the Two Pointer Technique involves sorting the array, then alternately selecting elements from the smallest and largest ends, creating a new array with maximum-minimum ordering.
Example:
Input:
arr[] = {1, 2, 3, 4, 5, 6, 7}
Output:
arr[] = {7, 1, 6, 2, 5, 3, 4}
Input:
arr[] = {1, 2, 3, 4, 5, 6}
Output:
arr[] = {6, 1, 5, 2, 4, 3}
There are several methods that can be used to Rearrange an array in maximum minimum form using the Two Pointer Technique in JavaScript, which is listed below:
We will explore all the above methods along with their basic implementation with the help of examples.
Using an auxiliary array
The approach uses an auxiliary array to temporarily store modified elements. It employs 'small' and 'large' pointers tracking the smallest and largest values in the original array. A 'flag' toggles between placing the next element from 'small' or 'large'. The original array is iterated, filling the modified array accordingly and updating the small and large pointers. Finally, the modified array is copied back to the original array to achieve the desired rearrangement.
Syntax
const temp = new Array(n);
Example : In this example,the rearrange function creates a new array by alternately selecting elements from the smallest and largest ends of the original array. It modifies arr in-place, creating a maximum-minimum rearranged array.
JavaScript
function rearrange(arr) {
const n = arr.length;
const temp = new Array(n);
let small = 0;
let large = n - 1;
let flag = true;
for (let i = 0; i < n; i++) {
if (flag) {
temp[i] = arr[large--];
} else {
temp[i] = arr[small++];
}
flag = !flag;
}
for (let i = 0; i < n; i++) {
arr[i] = temp[i];
}
}
const arr = [1, 2, 3, 4, 5, 6];
console.log("Original Array");
console.log(arr.join(" "));
rearrange(arr);
console.log("\nModified Array");
console.log(arr.join(" "));
OutputOriginal Array
1 2 3 4 5 6
Modified Array
6 1 5 2 4 3
Using sort() method
In this approach,we perform sorting an array in ascending order and then rearranging it. It uses two pointers, one starting from the beginning and the other from the end, to create a new array in maximum-minimum form.
Syntax
arr.sort(compareFunction);
Example: In this example the rearrange function sorts an array in ascending order and then creates a new array in maximum-minimum form using two pointers. It's applied to arr1, and both the original and modified arrays are displayed in the console.
JavaScript
function rearrange(arr) {
arr.sort((a, b) => a - b);
const n = arr.length;
const result = [];
for (let left = 0, right = n - 1;
left <= right; left++,
right--) {
result.push(arr[right]);
if (left !== right) {
result.push(arr[left]);
}
}
return result;
}
const arr1 = [1, 2, 3, 4, 5, 6];
const result = rearrange(arr1);
console.log("orignal array :", arr1)
console.log("Modified array :", result);
Outputorignal array : [ 1, 2, 3, 4, 5, 6 ]
Modified array : [ 6, 1, 5, 2, 4, 3 ]
In-Place Rearrangement with Two Pointers
Idea:
- Sort the array: Start by sorting the array in ascending order.
- Use two pointers: One pointer starts from the beginning (
small
), and the other pointer starts from the end (large
) of the sorted array. - Modify in place: Use a temporary variable to store values during the rearrangement to avoid overwriting data.
Steps:
- Sort the Array: First, sort the array in ascending order.
- Use Two Pointers:
- Initialize one pointer (
small
) at the beginning and the other pointer (large
) at the end of the sorted array. - Alternate between the two pointers, placing the elements from the end (largest) and then from the beginning (smallest) into the appropriate positions.
- Directly Modify the Original Array: Using a temporary variable, place the largest and smallest values alternately in the original array.
Example:
JavaScript
function rearrange(arr) {
const n = arr.length;
arr.sort((a, b) => a - b);
let small = 0;
let large = n - 1;
let temp = arr.slice();
for (let i = 0; i < n; i++) {
if (i % 2 === 0) {
arr[i] = temp[large--];
} else {
arr[i] = temp[small++];
}
}
}
const arr = [1, 2, 3, 4, 5, 6];
console.log("Original Array");
console.log(arr.join(" "));
rearrange(arr);
console.log("\nModified Array");
console.log(arr.join(" "));
OutputOriginal Array
1 2 3 4 5 6
Modified Array
6 1 5 2 4 3
Similar Reads
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read