我需要一些帮助。我的教授给了我们一个作业,我们只需要将这些代码“提取”为一个方法即可。有办法吗?这是一个堆代码排序算法。我目前确实对编程有一点了解,请耐心等待。你能帮助我吗?
import java.util.Arrays;
import java.util.Scanner;
class HeapSort {
private static Scanner sc;
public static void main(String args[]) {
sc = new Scanner(System.in);
System.out.println("Enter no of terms");
int n = sc.nextInt();
System.out.println("Enter the terms");
int arr[] = new int[n];
for (int i = 0; i < n; i++)
arr[i] = sc.nextInt();
System.out.println("The unsorted array is:");
System.out.println(Arrays.toString(arr));
heap(arr);
System.out.println("The sorted array is:");
System.out.println(Arrays.toString(arr));
}
static void heapify(int a[], int n, int i) {
int max, child;
child = 2 * i + 1;
max = i;
if (child < n)
if (a[child] > a[max])
max = child;
if (child + 1 < n)
if (a[child + 1] > a[max])
max = child + 1;
if (max != i) {
int temp = a[i];
a[i] = a[max];
a[max] = temp;
heapify(a, n, max);
}
}
static void buildheap(int a[]) {
for (int i = a.length / 2 - 1; i >= 0; i--)
heapify(a, a.length, i);
}
static void heap(int a[]) {
buildheap(a);
for (int i = a.length - 1; i >= 1; i--) {
int temp = a[0];
a[0] = a[i];
a[i] = temp;
heapify(a, i, 0);
}
}
}
答案 0 :(得分:1)
您只需将每个方法调用替换为方法的实际主体,即可到达那里。当然,由于方法参数的命名不正确,这将很快导致各种混乱。
但是这里(或可能是您实际的家庭作业)的真正挑战在于,您必须重做 heapify()
方法以不使用递归。换句话说:您必须使用递归对堆进行无排序。例如,您可以找到一些指南here。
当然:此代码已经很难阅读。强制将所有代码合并为一个方法将使其变得不可读且不便于人类理解。这就像是良好做法的完全相反!
答案 1 :(得分:0)
您可以做的一件事是将每个方法中的所有代码替换为该方法被调用的地方。
例如,您可以将所有代码移至被调用heap(arr)的位置,而无需继续调用heap(arr),然后继续处理其余代码。