我的逻辑中导致无限循环的缺陷在哪里?

时间:2015-07-04 21:10:15

标签: c++ algorithm pointers

我正在尝试"编码高尔夫"键入问题以准备面试。目前我正在尝试将数组的奇数元素移动到后面(不必保留顺序)。我已经多次查看过我的逻辑,并且无法想到任何可能导致无限循环的情况。但是,当我尝试运行它时,我得到Timeout。我已经评论了我的思考过程供你看。

#include <iostream>

void int_swap (int *pi1, int *pi2)
{
    int temp = *pi1;
    *pi1 = *pi2; 
    *pi2 = temp;
}

void odds_to_back (int *arr, size_t n)
{
    int * end = arr + n; // get pointer to 1 off the end of the array
    if (arr == end) return; // handle case of empty array
    --end; // move pointer to last element of the array
    while (arr != end) 
    {
       if (*arr % 2) // if first pointer is odd
       {
           if (!(*end % 2)) // if second pointer is even
           {
              int_swap(arr, end); // swap first and second
              ++arr; // increment first
           }
           else // second pointer is odd
           {
              while ((*end % 2) && arr != end) --end; // move second pointer towards first until second pointer is even or hits the first
           }
       }
       else // if first is even
       {
          ++arr; // increment first
       }
    }      

}

int main ( )
{
   int myArray [] = {1, 3, 5, 6, 19, 1, 2, 2};
   size_t N = sizeof(myArray)/sizeof(int);
   odds_to_back(myArray, N);
   for (size_t i = 0; i < N; ++i) std::cout << myArray[i] << " ";
   return 0;
}

1 个答案:

答案 0 :(得分:0)

哦,这很难。您正在呼叫swap (arr, end)而不是您自己的int_swap。所以,至少在我的test code中调用了更改指针(而不是指向的值)的函数std::swap

将来电更改为int_swap looks promising