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
First, count the number k of negative elements.
Then, you know that the first k numbers of the array (first part of the array) should be negative.
The following N - k elements should be positive after sorting the array.
You maintain two counters of how many elements respect those conditions in both parts of the array and increment it at each step until you know that one part is OK (counter is equal to the size of that part). Then the other part is OK too.
This requires O(1) storage and takes O(N) time.
Implementation in C++ :
#include
#include
using namespace std;
void swap(vector& L, int i, int j) {
int tmp = L[i];
L[i] = L[j];
L[j] = tmp;
}
void signSort(vector& L) {
int cntNeg = 0, i = 0, j = 0;
for (vector::iterator it = L.begin(); it < L.end(); ++it) {
if (*it < 0) ++cntNeg;
}
while (i < cntNeg && cntNeg + j < L.size()) {
if (L[i] >= 0) {
swap(L, i, cntNeg + j);
++j;
} else {
++i;
}
}
}
int main(int argc, char **argv) {
vector L;
L.push_back(-1);
L.push_back(1);
L.push_back(3);
L.push_back(-2);
L.push_back(2);
signSort(L);
for (vector::iterator it = L.begin(); it != L.end(); ++it) {
cout << *it << endl;
}
return 0;
}