
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Large to Small Sorting Algorithm of already sorted array in JavaScript
Suppose we have an array of integers that is already sorted in the increasing order. We are required to write a JavaScript function that without using the inbuilt Array.prototype.sort() method sorts the array like the following −
First number should be the maximum
Second number should be the minimum
Third number should be the 2nd maximum
Fourth number should be the 2nd minimum
And so on.
For example −
If the input array is −
const arr = [1, 2, 3, 4, 5, 6];
Then the output should be −
const output = [ 6, 1, 5, 2, 4, 3 ];
Example
Following is the code −
const arr = [1, 2, 3, 4, 5, 6]; const alternativeSort = (arr = []) => { const res = []; let left = 0; let right = arr.length - 1; while (res.length < arr.length) { res.push(arr[right]); if (left !== right) { res.push(arr[left]); } left++; right--; }; return res; }; console.log(alternativeSort(arr));
Output
Following is the console output −
[ 6, 1, 5, 2, 4, 3 ]
- Related Questions & Answers
- Sorting an already sorted internal table in ABAP
- Algorithm for sorting array of numbers into sets in JavaScript
- Special type of sorting algorithm in JavaScript
- Large to Small Sort in C++
- JavaScript - Check if array is sorted (irrespective of the order of sorting)
- Uneven sorting of array in JavaScript
- Sorting parts of array separately in JavaScript
- Alternative sorting of an array in JavaScript
- Sorting Array Elements in Javascript
- Sorting an array of binary values - JavaScript
- How to set Large icon instead of small icon on Android Notification?
- Sorting an array of objects by an array JavaScript
- JavaScript array sorting by level
- Sorting array according to increasing frequency of elements in JavaScript
- Sorting Array based on another array JavaScript
Advertisements