Jalan Technologies Assignment

mail@pastecode.io avatar
unknown
javascript
a year ago
1.0 kB
2
Indexable
Never
// Time Complexity - O(nlogn) + O(n) =~ O(nlogn)
// Space Complexity - O(1)

function shuffle(arr){
	arr.sort((a,b) => a - b);
	for(let i = 1; i < arr.length - 1; i += 2){
		const temp = arr[i];
		arr[i] = arr[i + 1];
		arr[i + 1] = temp;
	}
	return arr;
}

// Test case 1: Normal Input
const input1 = [2, 1, 5, 3, 11, 7];
const output1 = shuffle(input1);
console.log(output1); // [1, 3, 2, 7, 5, 11]

// Test case 2: Input with duplicates 
const input2 = [1, 2, 3, 3, 2, 1]
const output2 = shuffle(input2);
console.log(output2); // [1, 2, 1, 3, 2, 3]

// Test case 3: Input with Negative Numbers
const input3 = [-2, 5, -1, 3, 0, 7];
const output3 = shuffle(input3);
console.log(output3); // [-2, 0, -1, 5, 3, 7]

// Test case 4: Input with Single element
const input4 = [12];
const output4 = shuffle(input4);
console.log(output4);

// Test case 5: Input with even length
const input5 = [1, 2, 3, 4];
const output5 = shuffle(input5);
console.log(output5); // [1, 3, 2, 4]