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
Swapping even and odd index pairs internally in JavaScript
We are required to write a JavaScript function that takes in an array of literals as the first and the only argument.
Our function should swap each consecutive even index with each other, and swap each consecutive odd indexes with each other. The function should do these swappings in place.
For example, if the input array is:
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8];
Then the array should become:
const output = [2, 3, 0, 1, 6, 7, 4, 5, 8];
Because 0 and 2 get swapped, 1 and 3 get swapped, 4 and 6 get swapped, 5 and 7 get swapped, and finally 8 remains the same since it has no pair.
How It Works
The algorithm processes the array in groups of 4 elements. For each group, it swaps:
- Even indices: positions 0 ? 2, then 4 ? 6, etc.
- Odd indices: positions 1 ? 3, then 5 ? 7, etc.
Example
Following is the implementation:
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8];
const swapPairs = (arr = []) => {
const swap = (array, ind1, ind2) => {
const temp = array[ind1];
array[ind1] = array[ind2];
array[ind2] = temp;
};
let i = 0;
// Process groups of 4 elements
for(; i + 3 < arr.length; i += 4){
swap(arr, i, i + 2); // Swap even indices
swap(arr, i + 1, i + 3); // Swap odd indices
};
// Handle remaining elements if array length is not divisible by 4
if (i + 2 < arr.length){
swap(arr, i, i + 2);
};
};
swapPairs(arr);
console.log(arr);
Output
[ 2, 3, 0, 1, 6, 7, 4, 5, 8 ]
Alternative Approach
Here's a cleaner version using array destructuring for swapping:
const arr2 = [0, 1, 2, 3, 4, 5, 6, 7, 8];
const swapPairsClean = (arr) => {
for (let i = 0; i + 3 < arr.length; i += 4) {
// Swap even indices using destructuring
[arr[i], arr[i + 2]] = [arr[i + 2], arr[i]];
// Swap odd indices using destructuring
[arr[i + 1], arr[i + 3]] = [arr[i + 3], arr[i + 1]];
}
// Handle remaining even pair
const remaining = arr.length % 4;
if (remaining >= 3) {
const lastGroupStart = arr.length - remaining;
[arr[lastGroupStart], arr[lastGroupStart + 2]] = [arr[lastGroupStart + 2], arr[lastGroupStart]];
}
};
swapPairsClean(arr2);
console.log(arr2);
Output
[ 2, 3, 0, 1, 6, 7, 4, 5, 8 ]
Conclusion
This algorithm efficiently swaps even and odd index pairs by processing the array in groups of 4 elements. The swap operation is done in-place, modifying the original array without requiring additional memory space.
