2017-03-02 44 views
1

我一直在盯着这个,我无法弄清楚我做错了什么。我正在尝试编写一个重新排序奇数的函数,使其位于数组前面。赔率和均等的内在顺序并不重要,这意味着[3,1,4,2]或[1,3,2,4]都是可以接受的。拆分奇偶功能订购赔率和平价

目前,如果我初始化int arr[5] = {3,6,4,1,12}我得到3,4,1,6,2的输出努力弄清楚我做错了什么。下面

代码:

void SplitParity(int arr[], int arrSize) 
{ 
    int tempValueHolder; 

    for (int indexCounter = 0; indexCounter < arrSize; indexCounter++) 
    { 
     //Iterate through each index checking for odd 
     if (arr[indexCounter] % 2 == 0) 
     { 
      tempValueHolder = arr[indexCounter]; 

      //If Odd.....shift all indexes forward and move current to the back 
      for (int innerCounter = indexCounter; innerCounter < arrSize; innerCounter++) 
       arr[innerCounter] = arr[innerCounter + 1]; 

      arr[arrSize - 1] = tempValueHolder; 
     } 
    } 
} 
+0

可能的复制[按偶数和奇数排序](http://stackoverflow.com/questions/13416712/sort-by-even-and-odd-numbers) – chema989

回答

0

你忘了一切转移后,必须看indexCounter再次(你不知道的是,在循环的第一次迭代到达你这么做的时候arr[indexCounter] = arr[indexCounter+ 1];值正确与否)

简单的解决办法是刚过arr[arrSize - 1] = tempValueHolder;

这也是令人难以置信的innefficient,我建议你看看STD添加indexCounter --; ::分区

0

使用标准算法与正确的定义比较功能:

#include <iterator> 
#include <iostream> 
#include <algorithm> 

template<class T> 
bool is_odd(const T& value) 
{ 
    if (value & 1) 
     return true; 
    return false; 
} 

struct odd_first 
{ 
    template<class T> 
    bool operator()(const T& l, const T& r) const { 
     if (is_odd(l)) 
     { 
      if (is_odd(r)) 
       return false; 
      return true; 
     } 
     else 
      return false; 
    } 
}; 



int main() 
{ 
    int vals[] = { 5, 6, 7, 8, 9, 1, 2, 3, 4, 0 }; 

    std::sort(std::begin(vals), std::end(vals), odd_first()); 
    std::copy(std::begin(vals), std::end(vals), std::ostream_iterator<int>(std::cout, ", ")); 
    std::cout << std::endl; 
} 

预期输出:

5, 7, 9, 1, 3, 6, 8, 2, 4, 0, 

按Fezvez的建议,性病::分区:

#include <iterator> 
#include <iostream> 
#include <algorithm> 

struct is_odd 
{ 
    template<class T> 
    bool operator()(const T& value) const 
    { 
     if (value & 1) 
      return true; 
     return false; 
    } 
}; 

int main() 
{ 
    int vals[] = { 5, 6, 7, 8, 9, 1, 2, 3, 4, 0 }; 

    std::partition(std::begin(vals), std::end(vals), is_odd()); 
    std::copy(std::begin(vals), std::end(vals), std::ostream_iterator<int>(std::cout, ", ")); 
    std::cout << std::endl; 
} 
0

你可以做这么多,用std::sort更容易:Demo

std::sort(std::begin(arr), std::end(arr), [](int lhs, int rhs){ 
    return (lhs % 2 == 1 && rhs % 2 == 0); 
}); 

输出:

3 1 6 4 12 

或者,如果你希望中的内部排序奇数和偶数:Demo

std::sort(std::begin(arr), std::end(arr), [](int lhs, int rhs){ 
     int l_res = lhs % 2; 
     int r_res = rhs % 2; 
     if (l_res == r_res) 
      return lhs < rhs; 
     return (l_res == 1 && r_res == 0); 
    }); 

输出:

1 3 4 6 12