Блог пользователя zzczzzzz

Автор zzczzzzz, история, 7 недель назад, По-английски
Given an array of integers, our goal is to rearrange its elements so that all odd numbers are on the left side and all even numbers are on the right side, while keeping the relative order of elements unchanged.
 How would you do?
  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

»
7 недель назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Make an auxiliary array, and loop over the given array twice.

Get all the odds on the first round and all the evens on the second.

»
7 недель назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

in 0 based indexing, swap each ith element with (2*i)th element for first half of the array, you will get the desired arrangement

»
7 недель назад, # |
Rev. 2   Проголосовать: нравится +3 Проголосовать: не нравится

I would use STL:

std::stable_partition(a.begin(), a.end(), [](int x) { return x % 2 != 0; });

»
7 недель назад, # |
  Проголосовать: нравится 0 Проголосовать: не нравится

Use stable partition. Stable partition rearranges in True first order. So your condition of partition should be i % 2. stable_partition(all(A), [] (int i) {return i % 2;});