- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sorting array of exactly three unique repeating elements in JavaScript
Suppose we have an array of Numbers that contains any frequency of exactly three elements - 1, 0 and 1 like this −
const arr = [1, 1, 0, -1, 1, 0, -1, 1, 0, 0, 1];
We are required to write a JavaScript function that takes in one such array. The function should simply sort this special array in place i.e., without using any extra array to store the values.
The only condition is that our function should be a linear time function (using only one iteration).
Example
Following is the code −
const arr = [1, 1, 0, -1, 1, 0, -1, 1, 0, 0, 1]; const sortSpecialArray = (arr = []) => { const swap = (a, b) => { let middle = arr[a] arr[a] = arr[b] arr[b] = middle }; let left = 0; let middle = 0; let right = arr.length-1; while(middle <= right){ if(arr[middle] === -1){ swap(left++, middle++); }else if(arr[middle] === 0){ middle++; }else if(arr[middle] === 1){ swap(right--, middle); } }; }; sortSpecialArray(arr); console.log(arr);
Output
Following is the console output −
[ -1, -1, 0, 0, 0, 0, 1, 1, 1, 1, 1 ]
- Related Articles
- Count unique elements in array without sorting JavaScript
- Unique sort (removing duplicates and sorting an array) in JavaScript
- Finding array intersection and including repeating elements in JavaScript
- Sorting array according to increasing frequency of elements in JavaScript
- Sorting array based on increasing frequency of elements in JavaScript
- Sum of all the non-repeating elements of an array JavaScript
- Counting unique elements in an array in JavaScript
- Unique number of occurrences of elements in an array in JavaScript
- JavaScript construct an array with elements repeating from a string
- Uneven sorting of array in JavaScript
- Sorting elements of stack using JavaScript
- Sorting an array including the elements present in the subarrays in JavaScript
- Program to count number of sublists with exactly k unique elements in Python
- Alternative sorting of an array in JavaScript
- Sorting parts of array separately in JavaScript

Advertisements