This is one of an interview question which I had recently. I would like to know others perception of approach for this problem.
Question:
Yo
Here's my (complete) stab at it in C#. It generates the list and sticks random employees in, so make numberOfEmployees
whatever you like. I realize there is probably a simpler way of doing this, because the original poster specified that there are an equal amount of 0-dept employees as 1-dept employees, but I couldn't help myself.
struct Employee
{
public Employee(string name, int dept)
{
this.name = name;
this.dept = dept;
}
public string name;
public int dept;
}
class Program
{
static void Main(string[] args)
{
int numberOfEmployees = 100;
Random r = new Random();
Employee[] emps = new Employee[numberOfEmployees];
var empBuf = new Employee[numberOfEmployees];
int nextAvail = 0;
// Initialize array of employees with random data
for (int i = 0; i < numberOfEmployees; i++)
{
emps[i] = new Employee("x" + i.ToString(), r.Next(0, 2));
}
Console.WriteLine("Old list:");
foreach (var e in emps)
{
Console.WriteLine("Name: {0}, Dept: {1}", e.name, e.dept);
}
// throw employees with dept == 1 in first
for (int i = 0; i < numberOfEmployees; i++)
{
if (emps[i].dept == 1)
{
empBuf[nextAvail] = emps[i];
nextAvail++;
}
}
// stick the employees with dept == 0 in last
for (int i = 0; i < numberOfEmployees; i++)
{
if (emps[i].dept == 0)
{
empBuf[nextAvail] = emps[i];
nextAvail++;
}
}
Console.WriteLine("New list:");
foreach (Employee e in empBuf)
{
Console.WriteLine("Name: {0}, Dept: {1}", e.name, e.dept);
}
}
}