【问题标题】:Looking for help with implementation of a heap data structure寻求有关实现堆数据结构的帮助
【发布时间】:2010-05-28 16:00:14
【问题描述】:

我有一个堆上的操作,一个固定操作。这是代码:

public class Heap {

    public static void fixdown (int a[],int k,int n) {
        while (2*k<=n) {
            int j=2*k;
            if (j<n && a[j]<a[j+1]) j++;
            if (!(a[k]<a[j])) break;
            swap(a,k,j);
            k=j; 
        }
    }

    public  static void main (String[]args) {
        int a[]=new int[]{12,15,20,29,23,22,17,40,26,35,19,51};
        fixdown(a,1,a.length);
        for (int i=0;i<a.length;i++) {
            System.out.println(a[i]);
        }
    }

    public static void swap (int a[],int i,int j) {
        int t=a[i];
        a[i]=a[j];
        a[j]=t;
    }
}

更新:我已经改了,现在没有错误了。

//结果是

12
29
20
40
23
22
17
15
26
35
19
51

【问题讨论】:

  • 查看 fixdown 并查看它对那个值的作用。很好地用于单元测试。
  • 我建议使用更具描述性的变量名称。它将帮助您避免小错误

标签: java algorithm arrays


【解决方案1】:

a[j]=k;

你可能想要:

a[j]=t;


关于数组声明

请不要养成这样声明数组的习惯:

int x[];

你应该把括号放在类型中,而不是标识符

int[] x;

相关问题

【讨论】:

  • polygenelubricants 请看我的输出,我确定它是正确的,但你能建议我或检查一下吗?
  • re: arrays - 虽然我个人使用type[] ident; 进行声明,但我确实看到它在哪里被引用为“约定”,您愿意详细说明其背后的理由吗?我碰巧以“正确的方式”选择了它,但我看不出有什么理由不鼓励它。
【解决方案2】:

你有a[j]=k;

或许应该是a[j]=t;

【讨论】:

    【解决方案3】:

    那些行:

    for (int i=0;i<a.length;i++){
     System.out.println(a[i]);
    

    建议,您的数组中的索引是基于 0 的。如果是这样,索引 i 处元素的左右子元素的索引应该计算为

    leftchild_index = 2*i+1;
    rightchild_index = 2*i+2; // rightchild_index = leftchild_index + 1
    

    a[0] 的左孩子是a[1],右孩子是a[2]

    如果参数n是包含堆的数组的长度,则需要修正一些条件

    while(2*k<=n){
    

    应该改为:

    while(2*k + 1 < n){
    

    int j=2*k;
        if (j<n && a[j]<a[j+1])   j++;
    

    应该改为

    int j = 2 * k + 1;
        if (j < n - 1 && a[j] < a[j+1])   j++;
    

    否则,您将越界访问数组。

    【讨论】:

    • 您也可以将右描述为 rightchild = leftchild + 1; ^^
    【解决方案4】:

    代码在当前缩进状态下很难阅读,但我认为a[j]=k; 应该是a[j]=t;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-23
      • 2012-01-21
      • 2017-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-02
      相关资源
      最近更新 更多