Start learning free

LESSON 185 OF 289 · LOOPING OVER ARRAY INDICES

Employee of the Year V5 in C#: Top 2 Without Sorting

Practice Read the full explanation

Hand out bonuses to the top 2 most productive employees: the best one first, then the second best. You don't need any sorting. Find the best employee with the loop from v4, then find the best of the other employees with a second loop.

You start with:

        string[] names = {"John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"};
        int[] productivities = {83, 133, 97, 150, 120};
        int[] salaries = {135000, 335000, 210000, 250000, 180000};

Build:

Alice Chen: $37500
Mary Jane: $50250

Rules:

  • Index i in all three arrays refers to the same employee.
  • The best employee is the one with the highest productivity; the second best is the one with the highest productivity among all the other employees.
  • If two employees have the same productivity, the one listed first wins.
  • Each bonus is 15% of the salary, rounded down (with integer division).
  • Print two lines, the best employee first: name: $bonus.

Find the best employee first, exactly as in v4. Remember: strictly greater, so the first listed wins a tie.

For the second place, loop over all the indices and ignore the best one. The whole condition is if (i != bestIndex && (secondIndex == -1 || productivities[i] > productivities[secondIndex])) {. "Nobody chosen yet" must also let an employee in.

        string[] names = {"John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"};
        int[] productivities = {83, 133, 97, 150, 120};
        int[] salaries = {135000, 335000, 210000, 250000, 180000};

        int bestIndex = 0;
        for (int i = 1; i < names.Length; i++) {
            if (productivities[i] > productivities[bestIndex]) {
                bestIndex = i;
            }
        }
        int secondIndex = -1;
        for (int i = 0; i < names.Length; i++) {
            if (i != bestIndex && (secondIndex == -1 || productivities[i] > productivities[secondIndex])) {
                secondIndex = i;
            }
        }
        int bestBonus = salaries[bestIndex] * 15 / 100;
        int secondBonus = salaries[secondIndex] * 15 / 100;
        Console.WriteLine(names[bestIndex] + ": $" + bestBonus);
        Console.WriteLine(names[secondIndex] + ": $" + secondBonus);

STEP 1 OF 10
    Ctrl + Enter to check

    C# · LOOPING OVER ARRAY INDICES

    Employee Of The Year V5 in C#, explained

    Problem overview

    This version gives bonuses to the top two employees, best first and second best next. The data is the same three parallel arrays as before: names, productivities and salaries, where one index describes one employee. Each bonus is 15% of that employee's salary, rounded down with integer division. The second best is the one with the highest productivity among all the other employees. On equal productivity, the one listed first wins. Each line has the form name: $bonus.

    For the starter data, Alice Chen (150) is first and Mary Jane (133) is second:

    Alice Chen: $37500
    Mary Jane: $50250

    The previous version found the best index with one loop. This version keeps that loop and adds a second one for the runner-up.

    Approach: two passes, the second skipping the winner

    You could sort the employees by productivity and take the first two, but sorting three parallel arrays together is awkward and unnecessary. Two scans do the job.

    The first scan is the one already built: bestIndex starts at 0 and changes when someone has a strictly higher productivity. The second scan looks for the best employee except bestIndex. It starts from secondIndex = -1, which means "nobody chosen yet", since no employee has index -1. For each i, the employee qualifies if both hold:

    • i != bestIndex: the best employee already has first place.
    • Either nobody is chosen yet (secondIndex == -1), or the productivity at i is strictly greater than the one at secondIndex.

    The -1 case matters because there is nothing to compare against for the first qualifying employee. The condition is written so that productivities[secondIndex] is never evaluated while secondIndex is -1: the || operator stops as soon as its left side is true. Without that, reading index -1 would throw an exception.

    Step by step

    1. Find the best index. Set bestIndex to 0 and loop i from 1 while i < names.Length, updating bestIndex when productivities[i] is strictly greater than productivities[bestIndex]. This is the same loop as in the last version.
    2. Create secondIndex and set it to -1. It marks "nobody yet".
    3. Write a second loop from 0. It starts at 0 because the best employee can be anywhere in the list. They are skipped inside the loop instead of being excluded by the start.
    4. Inside it, write the if. It requires i != bestIndex, and either secondIndex == -1 or productivities[i] > productivities[secondIndex]. When all of that holds, set secondIndex = i.
    5. Compute bestBonus and secondBonus as salaries[index] * 15 / 100 for each index.
    6. Print the best employee as the name, a colon, a dollar sign and the bonus, then print the second best on the next line in the same form.

    The solution in C#

            string[] names = {"John Doe", "Mary Jane", "Bob Smith", "Alice Chen", "Carlos Diaz"};
            int[] productivities = {83, 133, 97, 150, 120};
            int[] salaries = {135000, 335000, 210000, 250000, 180000};
    
            int bestIndex = 0;
            for (int i = 1; i < names.Length; i++) {
                if (productivities[i] > productivities[bestIndex]) {
                    bestIndex = i;
                }
            }
            int secondIndex = -1;
            for (int i = 0; i < names.Length; i++) {
                if (i != bestIndex && (secondIndex == -1 || productivities[i] > productivities[secondIndex])) {
                    secondIndex = i;
                }
            }
            int bestBonus = salaries[bestIndex] * 15 / 100;
            int secondBonus = salaries[secondIndex] * 15 / 100;
            Console.WriteLine(names[bestIndex] + ": $" + bestBonus);
            Console.WriteLine(names[secondIndex] + ": $" + secondBonus);
    

    Details worth knowing:

    • Two loops, one variable name. Both for loops declare int i. That is legal because the scope of a loop variable ends with its loop. Declaring i a second time while the first is still in scope would be an error.
    • Short-circuit evaluation. && and || evaluate their right side only when needed. Here secondIndex == -1 || productivities[i] > productivities[secondIndex] relies on that, as described above.
    • Precedence and parentheses. && binds tighter than ||. The parentheses around the || part make the condition mean "not the best, and (nobody yet or better)". Without them it would mean something different.
    • A sentinel value. -1 works as "none" because valid indexes start at 0. The code that uses secondIndex after the loop assumes it is no longer -1, which holds when the arrays have at least two employees.

    Complexity

    Time: O(n) for n employees: two passes, each doing constant work per element. Space: O(1), since only a few integers are stored. Sorting would cost O(n log n) and more code.

    Edge cases and common mistakes

    • Ties for the best score. With productivities 83, 150, 97, 150 and 120, employees 1 and 3 tie. The first loop picks employee 1 (Mary Jane) as best. The second loop skips her and finds Alice Chen. The output is Mary Jane: $50250 then Alice Chen: $37500.
    • Ties for second. With 83, 133, 97, 150 and 133, employees 1 and 4 tie for second. Strictly greater keeps the earlier one: Mary Jane.
    • The best employee is first or last. With productivities 200, 133, 97, 150 and 120, the output is John Doe, then Alice Chen. With 1, 2, 3, 4 and 5, it is Carlos Diaz, then Alice Chen. The skip works wherever the best employee sits.
    • Only two employees. With productivities 5 and 9, the first loop picks index 1 and the second loop picks index 0.
    • Only one employee. The second loop finds nobody, secondIndex stays -1 and salaries[secondIndex] throws an IndexOutOfRangeException. The lesson's data always has at least two.
    • Forgetting i != bestIndex. The second loop would pick the best employee again and print the same person twice.
    • Starting the second loop at 1. If the best employee is at the end of the list, employee 0 would never be considered for second place.

    Testing

    • The starter data gives Alice Chen: $37500 then Mary Jane: $50250.
    • Productivities 1, 2, 3, 4, 5 give Carlos Diaz: $27000 then Alice Chen: $37500.
    • Productivities 83, 150, 97, 150, 120 give Mary Jane: $50250 then Alice Chen: $37500.
    • Two employees A and B with productivities 5 and 9 and salaries 100000 and 200000 give B: $30000 then A: $15000.
    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free