separate odd and even numbers in an array in O(n) time complexity and O(1) space complexity

Problem: as title

Solution: same as partition algorithm in quick sort.

/**after processing, odd number is in the left part, even number in the right part*/
void separate(int a[], int size) {
  if (size <= 0) {
    return;
  }
  for(int i = 0, j = size -1, t = 0;i < j;) {
    for(; (i < j) && ((a[i] & 0x1) == 1); i++); //empty loop
    for(; (i < j) && ((a[j] & 0x1) == 0); j--); //empty loop
    if (i < j) {
       t = a[i];
       a[i] = a[j];
       a[j] = t;
       i++;
       j--;
    }
  }
}


你可能感兴趣的:(test)