![]() |
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: 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: Table of ContentWe will explore all the above methods along with their basic implementation with the help of examples. Using an auxiliary arrayThe 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. Syntaxconst 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
Output
Original Array 1 2 3 4 5 6 Modified Array 6 1 5 2 4 3 Using sort() methodIn 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. Syntaxarr.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
Output
orignal array : [ 1, 2, 3, 4, 5, 6 ] Modified array : [ 6, 1, 5, 2, 4, 3 ] |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |