我正在努力学习heapsort。我遵循伪代码指令,但是,我的程序没有正常工作。我已经调试了一个小时了,无法找到错误。有一些错误:首先,arraylist没有正确排序;第二,arraylist似乎是从max - >排序min,即使它假设来自min - >最大。 对不起初学者的问题。
import java.util.ArrayList;
import java.util.Random;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int n;
Scanner input = new Scanner(System.in);
ArrayList<Integer> intList = new ArrayList<Integer>();
Random rand = new Random();
int minMax = 7000;
System.out.print("Input a positive integer: ");
n = input.nextInt();
for (int i = 0; i < n; i++) {
intList.add(rand.nextInt(minMax * 2) - minMax);
}
System.out.println(intList);
Heapsort(intList);
System.out.println(intList);
}
// Heapsort
public static void Heapsort(ArrayList<Integer> num) {
build_MaxHeap(num);
int n = num.size() - 1;
for (int i = n; i > 0; i--) {
swap(num, 0, i);
n = n - 1;
max_heapify(num, 0);
}
}
// build max heap from arraylist
public static void build_MaxHeap(ArrayList<Integer> num) {
for (int i = (num.size() - 1) / 2; i >= 0; i--)
max_heapify(num, i);
}
// max heapify
public static void max_heapify(ArrayList<Integer> num, int i) {
int left = 2 * i;
int right = 2 * i + 1;
int max = i;
int n = num.size() - 1;
if (left <= n && num.get(left) > num.get(i))
max = left;
if (right <= n && num.get(right) > num.get(max))
max = right;
if (max != i) {
swap(num, i, max);
max_heapify(num, max);
}
}
// swap 2 numbers in arraylist
public static void swap(ArrayList<Integer> num, int i, int j) {
int temp = num.get(i);
num.set(i, num.get(j));
num.set(j, temp);
}
}