This is one of an interview question which I had recently. I would like to know others perception of approach for this problem.
Question:
You are given a structure which holds employee details with two elements, int
department and string
name.
struct Employee
{
string Name;
int Dept;
}
You are given details of N Employees, among which N/2 employees have Dept == 0
and N/2 employees have Dept == 1
, arranged in some arbitrary order. You need to sort the employee details based on their Dept
value and it should be stable i.e., the order of 1s and 0s in the original record should be maintained.
For example, given the following sample data:
Name Dept
X1 0
X2 1
X3 0
X4 1
X5 0
after sorting the result should be:
Name Dept
X2 1
X4 1
X1 0
X3 0
X5 0
The algorithm should be stable and the time complexity should be O(N), with constant space for additional variables (which means sorting should be done in-place).
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…