c++ - algorithm moves the array elements -


i can not figure out algorithm task, maybe have idea? task: move array array in first half elements of odd lines , second elements of pair of lines. simplest option move elements array, make 1 using temp variable?

input data array  = {1,2,3,4,5,6,7,8} output data array = {2,4,6,8,1,3,5,7} 

is homework? if not, use std::stable_partition():

struct iseven {     template<class t>     bool operator()(const t& v) const { return v % 2 == 0; } };  int* arr = {1,2,3,4,5,6,7,8}; int* mid = std::stable_partition(arr, arr+8, iseven()); 

if homework, instructor expects write algorithm. if don't have maintain ordering in input sequence can rather efficiently:

  1. find first element doesn't satisfy predicate (i.e., odd).
  2. find last element does satisfy predicate (i.e., even)
  3. swap 2 elements.
  4. repeat, starting positions found, until 2 positions meet.
  5. the point 2 positions meet middle of partition, numbers stop , odd numbers begin.

this how std::partition() works. if have maintain relative ordering in input array can still in-place, faster if use temporary buffer. copy elements don't match predicate buffer, , squeeze in place do. bring in elements don't match, @ end of array, in order.


Comments

Popular posts from this blog

asp.net - repeatedly call AddImageUrl(url) to assemble pdf document -

java - Android recognize cell phone with keyboard or not? -

iphone - How would you achieve a LED Scrolling effect? -