Created
August 15, 2022 14:31
-
-
Save mdpabel/6f521ef4dfa693d54cba78d2b8feb967 to your computer and use it in GitHub Desktop.
even odd swapping without using extra space
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const arr = [1,5,2,9,7,6] | |
/** | |
1 5 9 7 2 6 | |
l = 1 | |
r = 4 | |
1,5,2,9,7,6 | |
2 odd ? l++ | |
2 even ? r-- | |
else : l | |
*/ | |
let left = 0 | |
let right = arr.length - 1 | |
while(left < right){ | |
if(arr[left] % 2 == 1 && arr[right] % 2 == 1){ | |
left++ | |
}else if(arr[left] % 2 == 0 && arr[right] % 2 == 0){ | |
right-- | |
}else{ | |
if(arr[left] % 2 != 1 && arr[right] % 2 != 0){ | |
let temp = arr[right] | |
arr[right] = arr[left] | |
arr[left] = temp | |
} | |
left++ | |
right-- | |
} | |
} | |
console.log(arr) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment