假定所有雇员每周工作的小时数存储在一个二维数组中。1行包含7列,记录了一个雇员7天的工作小时数。编写一个程序,按照总工时降序显示。
package pack2;
public class Employee {
public static void main(String[] args) {
hour();
}
/**计算每个雇员每周工作的小时数*/
public static void hour() {
int[][] hours = {{2, 4, 3, 4, 5, 8, 8}, {7, 3, 4, 3, 3, 4, 4},
{3, 3, 4, 3, 3, 2, 2}, {9, 3, 4, 7, 3, 4, 1},
{3, 5, 4, 3, 6, 3, 8}, {3, 4, 4, 6, 3, 4, 4},
{3, 7, 4, 8, 3, 8, 4}, {6, 3, 5, 9, 2, 7, 9},};
int[] totalHours = new int[hours.length];
int[] employees = {0, 1, 2, 3, 4, 5, 6, 7};
for (int i = 0; i < hours.length; i++)
for (int j = 0; j < hours[i].length; j++)
totalHours[i] += hours[i][j];
sort(totalHours, employees);
for (int i = 0; i < employees.length; i++)
System.out.println("Employee "+employees[i]+"\tTotal hours: "+totalHours[i]);
}
/**排序*/
public static void sort(int[] totalHours, int[] employees) {
for (int i = 0; i < employees.length - 1; i++) {
int currentMax = totalHours[i];
int currentIndex = i;
for (int j = i + 1; j < employees.length; j++)
if(currentMax < totalHours[j]) {
currentMax = totalHours[j];
currentIndex = j;
}
if(currentIndex != i) {
totalHours[currentIndex] = totalHours[i];
totalHours[i] = currentMax;
int temp = employees[i];
employees[i] = employees[currentIndex];
employees[currentIndex] = temp;
}
}
}
}