Jim D
Jim D

Reputation: 31

Incorrect output/index with a "2D" array

I have this java code that's supposed to give you the sum of hours worked per employee per week then sort the total hours in a descending order. The problem is that when it compiles, the employee ID's are messed up.

Does anyone know why?

Thanks

static void list(Object[] a, Object n) {

    int empID = Arrays.binarySearch(a, n);
        System.out.println("Employee " + empID + " :  " + n);
}

public static void main(String[] args) {

    int[][] hours = new int[][]{
            {2, 2, 4, 3, 4, 3, 5, 9},
            {3,7, 5, 4, 3, 5, 9, 4},
            {12, 5, 9, 4, 3, 3, 2, 2},
            {4, 9, 3, 3, 5, 9, 4, 10},
            {5, 3, 5, 9, 3, 6, 3, 8},
            {6, 3, 4, 4, 6, 3, 14, 4},
            {7, 3, 7, 4, 8, 3, 5, 9},
            {8, 6, 3, 5, 9, 8, 7, 9}};

    Integer[] totalHours = new Integer[8];
    for (int i = 0; i < 8; i++) {
        int sum = 0;
    for (int j = 1; j < 8; j++) {
        sum += hours[i][j];
        totalHours[i] = sum;
    }

}


    Integer[] sorted;

    sorted = new Integer[totalHours.length];
        for (int i = 0; i < totalHours.length; i++) {
            sorted[i] = totalHours[i];
        }

    Arrays.sort(sorted, Collections.reverseOrder());
        for (int i = 0; i < sorted.length; i++) {

        }   

        for (int i = 0; i < sorted.length; i++) {
            list(totalHours, sorted[i]);
        }

}

Upvotes: 0

Views: 52

Answers (1)

sprinter
sprinter

Reputation: 27946

Ideally you would create an Employee class including an ID and hours worked. Once you have a list of employees you can happily search, sort, total etc.

For example:

class Employee {
    private final int id;
    private int[] hours;
    public int getTotalHours() {
        return Arrays.stream(hours).sum();
    }
}

List<Employee> employees;
Collections.sort(employees, (e1, e2) -> e1.getTotalHours() - e2.getTotalHours());

If for some reason you particularly don't want to create an Employee class and you want to continue to use the id as an index into the hours array, then you could create a separate array of the employee ids and sort that by total hours.

int[] employees = new int[hours.length];
for (int i = 0; i < hours.length; i++)
    employees[i] = i;
Arrays.sort(employees, (e1, e2) -> getTotalHours(e1) - getTotalHours(e2));

You would then have a sorted array of employee ids which are also indexes into your hours array.

But, frankly, this is a pretty hacky way to do it so create the Employee class if you can.

Upvotes: 1

Related Questions