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

来源:互联网 发布:严防网络泄密十条禁令 编辑:程序博客网 时间:2024/05/29 18:05

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--;    }  }}