Robel Sharma
Robel Sharma

Reputation: 972

Efficient Way to Arrange Odd and Even Data Sequentially

I have data like (1,2,3,4,5,6,7,8) .I want to arrange them in a way like (1,3,5,7,2,4,6,8) in n/2-2 swap without using any array and loop must be use 1 or less.

Note that i have to do the swap in existing array of number.If there is other way like without swap and without extra array use,

Please give me some advice.

Upvotes: 1

Views: 149

Answers (2)

wildplasser
wildplasser

Reputation: 44250

#include <stdio.h>
#include <string.h>

char array[26] = "ABcdEfGiHjklMNOPqrsTUVWxyZ" ;
#define COUNTOF(a_) (sizeof(a_)/sizeof(a_)[0])
#define IS_ODD(e) ((e)&0x20)
#define IS_EVEN(e) (!IS_ODD(e))

void doswap (char *ptr, unsigned sizl, unsigned sizr);
int main(void)
{
unsigned bot,limit,cut,top,size;

size = COUNTOF(array);
printf("Before:%26.26s\n", array);

    /* pass 1 count the number of EVEN chars */
for (limit=top=0; top < size; top++) {
    if ( IS_EVEN( array[top] ) ) limit++;
    }

    /* skip initial segment of EVEN  */
for (bot=0; bot < limit;bot++ ) {
    if ( IS_ODD(array[bot])) break;
    }

    /* Find leading strech of misplaced ODD + trailing stretch of EVEN */
for (cut=bot;bot < limit; cut = top) {
        /* count misplaced items */
    for (    ;cut < size && IS_ODD(array[cut]); cut++) {;}
        /* count shiftable items */
    for (top=cut;top < size && IS_EVEN(array[top]); top++) {;}

        /* Now, [bot...cut) and [cut...top) are two blocks 
        ** that need to be swapped: swap them */
    doswap(array+bot, cut-bot, top-cut);
    bot += top-cut;
    }

printf("Result:%26.26s\n", array);
return 0;
}

void doswap (char *ptr, unsigned sizl, unsigned sizr)
{
if (!sizl || !sizr) return;
if (sizl >= sizr) {
    char tmp[sizr];
    memcpy(tmp, ptr+sizl, sizr);
    memmove(ptr+sizr, ptr, sizl);
    memcpy(ptr, tmp, sizr);
    }
else {
    char tmp[sizr];
    memcpy(tmp, ptr, sizl);
    memmove(ptr, ptr+sizl, sizr);
    memcpy(ptr+sizl, tmp, sizl);
    }
}

Upvotes: 0

amit
amit

Reputation: 178471

maintain two pointers: p1,p2. p1 goes from start to end, p2 goes from end to start, and swap non matching elements.

pseudo code:

specialSort(array):
  p1 <- array.start()
  p2 <- array.end()
  while (p1 != p2): 
     if (*p1 %2 == 0):
         p1 <- p1 + 1;
         continue;
     if (*p2 %2 == 1):
         p2 <- p2 -1;
         continue;
     //when here, both p1 and p2 need a swap
     swap(p1,p2);

Note that complexity is O(n), at least one of p1 or p2 changes in every second iteration, so the loop cannot repeat more the 2*n=O(n) times. [we can find better bound, but it is not needed]. space complexity is trivially O(1), we allocate a constant amount of space: 2 pointers only.

Note2: if your language does not support pointers [i.e. java,ml,...], it can be replaced with indexes: i1 going from start to end, i2 going from end to start, with the same algorithm principle.

Upvotes: 1

Related Questions