有人可以告诉我我做错了什么,我制作了一个程序,它读取一个文件并使用最大堆按工资对它们进行排序,但输出结果与它们略有分类。
public static Employee[] employees = new Employee[6];
public static int counter = 0;
public static void main(String[] args) throws FileNotFoundException {
System.out.println("IDC");
Scanner scan = new Scanner(new File("Employernotes.txt"));
int id = 0;
String name = "";
double salary = 0;
String department = "";
String position = "";
int years = 0;
int index = 0;
while (scan.hasNext()) {
id = scan.nextInt();
name = scan.next();
salary = scan.nextDouble();
department = scan.next();
position = scan.next();
years = scan.nextInt();
employees[index] = new Employee(id, name, salary, department, position, years);
index++;
}
for (int kk = employees.length - 1; kk >= 0; kk--) {
heapM(employees, kk);
}
//PRINT
for (int krk = 0; krk < employees.length; krk++) {
System.out.println(employees[krk]);
}
}
public static void heapM(Employee[] employees, int i) {
int largest;
int left = 2 * i + 1;
int right = 2 * i + 2;
if (((left < employees.length) && (employees[left].getSalary() > employees[i].getSalary()))) {
largest = left;
} else {
largest = i;
}
if (((right < employees.length) && (employees[right].getSalary() > employees[largest].getSalary()))) {
largest = right;
}
if (largest != i) {
swap(i, largest);
heapM(employees, largest);
}
}
private static void swap(int i, int largest) {
Employee t = employees[i];
employees[i] = employees[largest];
employees[largest] = t;
}
输出结果为:
Salary: 8000000.0
Salary: 85000.0
Salary: 290000.0
Salary: 10000.0
Salary: 48000.0
Salary: 32000.0
答案 0 :(得分:0)
对于堆排序,您需要执行初始堆化以设置初始堆,然后在移动每个&#34;最大的#34;时重新调整(使用sift down)。元素到数组的末尾。维基文章: