Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用最大堆对文件进行排序_Java_Sorting - Fatal编程技术网

Java 使用最大堆对文件进行排序

Java 使用最大堆对文件进行排序,java,sorting,Java,Sorting,有人能告诉我我做错了什么吗?我制作了一个程序,可以读取一个文件,并使用max堆按工资对它们进行排序,但输出结果是稍微排序的 public static Employee[] employees = new Employee[6]; public static int counter = 0; public static void main(String[] args) throws FileNotFoundException { System.out.println("IDC");

有人能告诉我我做错了什么吗?我制作了一个程序,可以读取一个文件,并使用max堆按工资对它们进行排序,但输出结果是稍微排序的

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;

}

对于堆排序,您需要执行初始heapify来设置初始堆,然后在将每个“最大”元素移动到数组末尾时重新调整(使用向下筛选)。维基文章:

Salary: 8000000.0
Salary: 85000.0
Salary: 290000.0
Salary: 10000.0
Salary: 48000.0
Salary: 32000.0