Created
October 15, 2017 17:11
-
-
Save TechMaster/8a431280cf53f012d6570b4850733cf1 to your computer and use it in GitHub Desktop.
Move all even numbers to left, odd numbers to right
This file contains hidden or 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
| #include <iostream> | |
| #include <vector> | |
| using namespace std; | |
| /* | |
| Chuyển số chẵn về bên trái, số lẻ về bên phải | |
| http://algorithms.tutorialhorizon.com/separate-even-and-odd-integers-in-a-given-array/ | |
| int [] arrA = {1,2,3,4,6,8,7,12}; | |
| Output: [12, 2, 8, 4, 6, 3, 7, 1] | |
| */ | |
| int main() { | |
| vector<int> arr = {9, 10, 1, 2, 3, 4, 6, 8, 7, 12}; | |
| auto left = arr.begin(); | |
| auto right = arr.end() - 1; | |
| while (left < right) { | |
| if (*left % 2 == 0) { | |
| left++; | |
| } else if (*right % 2 == 0) { | |
| auto temp = *left; | |
| *left = *right; | |
| *right = temp; | |
| } | |
| if (*right % 2 == 1) { | |
| right--; | |
| } | |
| } | |
| for (auto i: arr) { | |
| cout << i << " "; | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment