Horje
Sorting Array of Exactly Three Unique Repeating Elements in JavaScript

Given an array of Numbers that contain any frequency of exactly three unique elements. Our task is to sort this array using JavaScript.

Examples: 

Input: arr[] = [3, 1, 3, 2, 1, 2, 1, 3, 2]
Output: [1, 1, 1, 2, 2, 2,3,3,3]

Input = arr[] =[1,2,3,1,2,3]
Output: [1,1,2,2,3,3]

Counting Sort with Extra Space

In this approach, we use counting sort to sort the array. We count the occurrences of each unique element and then construct the sorted array based on the counts.

Example: Implementation of a program to sort an array of exactly three unique repeating elements using Counting Sort with Extra Space

JavaScript
function sortArray(arr) {
    const counts = {};
    arr.forEach(num => {
        counts[num] = (counts[num] || 0) + 1;
    });

    const sortedArr = [];
    for (let i = 0; i < 3; i++) {
        const num = i + 1;
        if (counts[num]) {
            sortedArr.push(...Array(counts[num]).fill(num));
        }
    }

    return sortedArr;
}

const arr = [3, 1, 3, 2, 1, 2, 1, 3, 2];
const sortedArr = sortArray(arr);
console.log("Sorted array:", sortedArr);

Output
Sorted array: [
  1, 1, 1, 2, 2,
  2, 3, 3, 3
]

Time Complexity: O(n)

Auxiliary Space: O(n)

Three-Way Partitioning

In this approach we use three-way partitioning technique to sort the array in place. Here we maintain three pointers (low, mid, and high) to partition the array into three sections and thus sortiing them.

Example: Implementation of program to sort array of exactly three unique repeating elements using Three-Way Partitioning

JavaScript
function sortArray(arr) {
    let l = 0, m = 0, h = arr.length - 1;

    while (m <= h) {
        if (arr[m] === 1) {
            [arr[l], arr[m]] = [arr[m], arr[l]];
            l++;
            m++;
        } else if (arr[m] === 2) {
            m++;
        } else {
            [arr[m], arr[h]] = [arr[h], arr[m]];
            h--;
        }
    }

    return arr;
}

const arr = [3, 1, 3, 2, 1, 2, 1, 3, 2];
const sortedArr = sortArray(arr);
console.log("Sorted array:", sortedArr);

Output
Sorted array: [
  1, 1, 1, 2, 2,
  2, 3, 3, 3
]

Time Complexity: O(N),where n is the length of the input array

Auxiliary Space: O(1)




Reffered: https://www.geeksforgeeks.org


JavaScript

Related
How to Set an Expiration Date for Items in a Service Worker Cache using JavaScript? How to Set an Expiration Date for Items in a Service Worker Cache using JavaScript?
DFS using JavaScript DFS using JavaScript
JavaScript Program to Print all Palindromic Paths from Top Left to Bottom Right in a Matrix JavaScript Program to Print all Palindromic Paths from Top Left to Bottom Right in a Matrix
How to get Attribute Value from XML using JavaScript? How to get Attribute Value from XML using JavaScript?
Sort Mixed Alpha/Numeric array in JavaScript Sort Mixed Alpha/Numeric array in JavaScript

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
18