I recently came across a Microsoft Interview Question for Software Engineer.
Given an array of positive and negative integers, re-arrange it so that you
I hope this helps. This one has Time Complexity O(n^2)
#include
int main() {
int a[] = {-3, 2, -5, 9, -2, -8, 6, 8, -1, 6};
int length = (sizeof(a) / sizeof(int));
int i, j = 0;
printf("Size of array: %d\n", sizeof(a));
for (i = 0; i < length; i++) {
if (i % 2 == 0 && a[i] < 0) {
for (j = i + 1; j < length; j++) {
if (a[j] > 0) {
int t = a[i];
a[i] = a[j];
a[j] = t;
break;
}
}
} else if (i % 2 == 1 && a[i] > 0) {
for (j = i + 1; j < length; j++) {
if (a[j] < 0) {
int t = a[i];
a[i] = a[j];
a[j] = t;
break;
}
}
}
}
for (i = 0; i < length; i++) {
printf("Value at %d: %d\n", i, a[i]);
}
return 0;
}
EDIT 1 This relies on the fact that numbers greater than zero are always at an even index and numbers less than zero are always at odd index
EDIT 2 Improved the code a little