Created
September 25, 2015 19:41
-
-
Save ishankhare07/e04270835820277c5fc6 to your computer and use it in GitHub Desktop.
arrange a mix of numbers in an array in alternating +ve & -ve while retaining the order
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include "stdio.h" | |
#include "stdlib.h" | |
#define size(x) ({ \ | |
sizeof(x) / sizeof(int); \ | |
}) | |
int main(void) { | |
int input[] = {4, -10, 2, -2, -7, 3, -3, 5, -4, -5, 1, -9, 0, -6, -1, -8}; | |
int *i, *neg, *pos; | |
int *separators[2]; // pointer to a 2x(not yet know size) array | |
neg = separators[0] = malloc(sizeof(int) * size(input)); | |
pos = separators[1] = malloc(sizeof(int) * size(input)); | |
for(i = input; i < input+size(input); i++) { | |
if(*i < 0) { // negative | |
*neg++ = *i; | |
} else { | |
*pos++ = *i; | |
} | |
} | |
neg = separators[0]; | |
pos = separators[1]; | |
i = input; | |
int cond1=1, cond2=1; | |
while(cond1 || cond2) { | |
// starting with -ve first | |
if (cond1 = (neg < separators[0]+size(separators[0]))) { | |
*i++ = *neg++; | |
} | |
if (cond2 = (pos < separators[1]+size(separators[1]))) { | |
*i++ = *pos++; | |
} | |
} | |
*i = '\0'; | |
for(i = input; i < input+size(input); i++) { | |
printf("%d ", *i); | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment