Start learning free

LESSON 183 OF 285 · LOOPING OVER ARRAY INDICES

Employee Of The Year V5 in Java: 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;
System.out.println(names[bestIndex] + ": $" + bestBonus);
System.out.println(names[secondIndex] + ": $" + secondBonus);

STEP 1 OF 10
    Ctrl + Enter to check

    JAVA · LOOPING OVER ARRAY INDICES

    Employee Of The Year V5 in Java, explained

    Problem overview

    This version hands out bonuses to the two most productive employees, best first. The data is the same three parallel arrays as before: names, productivities and salaries. The program prints two lines in the form name: $bonus, where the bonus is 15% of the salary, rounded down. Ties go to the employee listed first.

    In the starter data, Alice Chen has 150 and Mary Jane has 133, the two highest:

    Alice Chen: $37500
    Mary Jane: $50250

    The bonus for second place is larger because Mary's salary is larger. The ranking depends on productivity only.

    Approach: two scans, no sorting

    Sorting is not needed. The previous version already finds the best employee with one scan. For second place, run a second scan over everyone except the winner and keep the best of those. The same idea, "keep the best so far", is used twice with a different set of candidates.

    The first scan produces bestIndex. The second scan keeps secondIndex, which starts at -1. No employee has index -1, so it can mean "nobody chosen yet". That matters because the very first candidate in the second scan has nobody to be compared with and must be accepted automatically.

    Step by step

    1. Create bestIndex at 0. Employee 0 is the best known until beaten.
    2. Loop i from 1 while i < names.length.
    3. Replace bestIndex when productivities[i] is strictly greater than productivities[bestIndex]. Strict means the first listed wins ties.
    4. Create secondIndex at -1, meaning "nobody chosen yet".
    5. Write a second loop with i starting at 0. This time employee 0 may be second best, and the winner can sit anywhere in the list, so the loop must see every index and skip the winner inside the loop.
    6. Write the condition for a new second best. The employee must not be the best one (i != bestIndex), and either nobody is chosen yet (secondIndex == -1) or the productivity is strictly greater than that of secondIndex. When all that holds, set secondIndex = i.
    7. Compute bestBonus from salaries[bestIndex].
    8. Compute secondBonus the same way from salaries[secondIndex].
    9. Print the best employee as the name, a colon, a dollar sign and the bonus.
    10. Print the second best in the same form on the next line.

    The solution in Java

    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;
    System.out.println(names[bestIndex] + ": $" + bestBonus);
    System.out.println(names[secondIndex] + ": $" + secondBonus);
    

    The order inside the condition matters. Java's || stops as soon as its left side is true. When secondIndex == -1 is true, the right side productivities[secondIndex] is never evaluated, which is a good thing, because productivities[-1] would throw an exception.

    Tracing the second loop

    With the starter data, bestIndex is 3 after the first loop. This is what the second loop does:

    iEmployeesecondIndex after the check
    0John Doe, 830 (nobody chosen yet)
    1Mary Jane, 1331 (133 > 83)
    2Bob Smith, 971
    3Alice Chen, 1501 (this is the best employee, skipped)
    4Carlos Diaz, 1201

    The loop ends with secondIndex equal to 1, Mary Jane.

    The first loop is exactly the one from the previous version, so its trace is the same: bestIndex moves to 1 at i = 1 and to 3 at i = 3, and stays there.

    Complexity

    Two passes over n employees give O(n) time, and the extra space is O(1). Sorting would cost more (O(n log n)) and would also scramble the connection between the three parallel arrays.

    Edge cases and common mistakes

    Ties for first place

    With productivities {150, 133, 97, 150, 120}, John Doe and Alice Chen tie for first. The first scan picks John (index 0). The second scan skips him and picks Alice, so the output is John Doe: $20250 and Alice Chen: $37500. The tied employee is correctly ranked second.

    Ties for second place

    With productivities {83, 133, 97, 133, 120}, Mary Jane and Alice Chen tie at 133. The first scan picks Mary, the second scan picks Alice, and the output is Mary Jane: $50250 and Alice Chen: $37500.

    Using >= in the second scan

    The second scan needs the same strict comparison as the first. With >=, a later employee who ties with the current second best would replace them, so among equals the last one listed would be ranked second instead of the first one.

    Starting the second loop at 1

    Copying the first loop's i = 1 would never consider employee 0 for second place. When employee 0 is the second best, the program would pick the wrong person.

    Forgetting to skip the winner

    Without the i != bestIndex test, the second scan would simply find the best employee again, and both lines would show the same person.

    A team of one

    With a single employee, no index passes the test in the second loop, so secondIndex stays -1. Reading salaries[secondIndex] then throws ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 1. The lesson's data always has at least two employees.

    Key takeaways

    • A second "best so far" scan over everyone except the winner finds second place without sorting.
    • Use -1 as an "empty" index and let the condition accept the first candidate.
    • Put the emptiness check first in an ||, so the comparison that would fail is never evaluated.
    Keep going with Java1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free