Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Sorting binary string having an even decimal value using JavaScript
We are required to write a JavaScript function that takes in a string containing binary strings of length 3, all separated by spaces. Our function should sort only the even numbers (when converted from binary to decimal) in ascending order, while leaving all odd numbers in their original positions.
Problem
Given a string with binary numbers, we need to:
- Convert each binary string to its decimal equivalent
- Identify which numbers are even
- Sort only the even numbers in ascending order
- Keep odd numbers in their original positions
Example
Let's look at the binary strings and their decimal values:
- '101' = 5 (odd, stays in place)
- '111' = 7 (odd, stays in place)
- '100' = 4 (even, will be sorted)
- '001' = 1 (odd, stays in place)
- '010' = 2 (even, will be sorted)
const str = '101 111 100 001 010';
const sortEvenIncreasing = (str = '') => {
const sorter = (a, b) => {
const findInteger = bi => parseInt(bi, 2);
if(findInteger(a) % 2 === 1 || findInteger(b) % 2 === 1){
return 0;
};
return findInteger(a) - findInteger(b);
};
const res = str
.split(' ')
.sort(sorter)
.join(' ');
return res;
};
console.log(sortEvenIncreasing(str));
101 111 010 001 100
How It Works
The solution uses a custom sorting function that:
- Converts each binary string to decimal using
parseInt(bi, 2) - Checks if either number is odd using the modulo operator
% 2 === 1 - If either number is odd, returns 0 (no change in order)
- If both numbers are even, compares them for ascending order
Step-by-Step Breakdown
// Let's trace through the sorting process
const binaryNumbers = ['101', '111', '100', '001', '010'];
const decimalValues = binaryNumbers.map(bin => parseInt(bin, 2));
console.log('Decimal values:', decimalValues);
// Identify even and odd numbers
decimalValues.forEach((val, index) => {
const type = val % 2 === 0 ? 'even' : 'odd';
console.log(`${binaryNumbers[index]} (${val}) is ${type}`);
});
Decimal values: [ 5, 7, 4, 1, 2 ] 101 (5) is odd 111 (7) is odd 100 (4) is even 001 (1) is odd 010 (2) is even
Alternative Implementation
Here's a more explicit approach that separates even and odd numbers:
const sortEvenAlternative = (str = '') => {
const numbers = str.split(' ');
const evenNumbers = [];
const positions = [];
// Extract even numbers and their positions
numbers.forEach((bin, index) => {
const decimal = parseInt(bin, 2);
if (decimal % 2 === 0) {
evenNumbers.push(bin);
positions.push(index);
}
});
// Sort even numbers
evenNumbers.sort((a, b) => parseInt(a, 2) - parseInt(b, 2));
// Create result array
const result = [...numbers];
positions.forEach((pos, index) => {
result[pos] = evenNumbers[index];
});
return result.join(' ');
};
console.log(sortEvenAlternative('101 111 100 001 010'));
101 111 010 001 100
Conclusion
This solution demonstrates custom sorting in JavaScript by using a comparator function that selectively sorts only even decimal values while preserving the positions of odd numbers. The key is using parseInt(binary, 2) for binary-to-decimal conversion and returning 0 in the comparator to maintain original order for odd numbers.
