应用在Java中实现的HeapSort后,列表未排序

时间:2015-09-17 09:37:29

标签: java sorting

我正在尝试在java中实现heapSort但在执行后没有获取排序列表。你能告诉我这里做错了什么吗?我创建了一个方法Heapsort来对堆调用堆本身进行排序。一旦调用堆,它就会给我一个包含顶部最大元素的堆树。我假设我的交换或进一步的过程不能正常工作。这里有什么不对?

  public class HeapSort 
  {
   public static void main(String args[])
   {
    int a[]=new int[]{30,100,20,80,40,90,50,60};
    for(int i=0;i<a.length;i++)
    {
        System.out.print(a[i]+"\t");
    }
    System.out.println("");
    heapSort(a);
    for(int i=0;i<a.length;i++)
    {
        System.out.print(a[i]+"\t");
    }
}
public static void heapSort(int a[])
{
    int i, temp;
    for(i=a.length-1;i>=0;i--)
    {
        heap(a);
        temp=a[0];
        a[0]=a[i];
        a[i]=temp;
    }
}
public static void heap(int a[])
{
    int i,j,k,temp;
    for(i=0;i<a.length;i++)
    {
        j=i;
        k=(i-1)/2;
        while(k>=0&&a[j]>a[k])
        {
            temp=a[j];
            a[j]=a[k];
            a[k]=temp;
            j=j/2;
            k=k/2;
        }
    }
}
}

1 个答案:

答案 0 :(得分:4)

您应该尝试调试代码。

或者您可以使用旧样式并插入打印语句,这样您就可以在中间结果中看到模式。

heap()方法的开头和结尾添加print语句:

public static void heap(int a[])
{
    System.out.println("heap in : " + Arrays.toString(a));
    // existing code
    System.out.println("heap out: " + Arrays.toString(a));
}

输出

heap in : [30, 100, 20, 80, 40, 90, 50, 60]
heap out: [100, 90, 80, 60, 40, 20, 50, 30]
heap in : [30, 90, 80, 60, 40, 20, 50, 100]
heap out: [100, 90, 80, 60, 40, 20, 50, 30]
heap in : [50, 90, 80, 60, 40, 20, 100, 30]
heap out: [90, 60, 100, 50, 40, 20, 80, 30]
heap in : [20, 60, 100, 50, 40, 90, 80, 30]
heap out: [100, 90, 80, 30, 40, 60, 50, 20]
heap in : [40, 90, 80, 30, 100, 60, 50, 20]
heap out: [90, 100, 80, 30, 40, 60, 50, 20]
heap in : [30, 100, 80, 90, 40, 60, 50, 20]
heap out: [100, 90, 80, 30, 40, 60, 50, 20]
heap in : [80, 90, 100, 30, 40, 60, 50, 20]
heap out: [100, 80, 90, 30, 40, 60, 50, 20]
heap in : [80, 100, 90, 30, 40, 60, 50, 20]
heap out: [100, 80, 90, 30, 40, 60, 50, 20]

你看到了问题吗?

Heap Sort应该将最大值推到最后一个位置,然后是第二个到最后一个位置,依此类推...

但是,100继续前进。为什么?因为您将整个数组发送到每次电话上的heap()

heap(int a[])更改为heap(int a[], int len)i<a.length方法中将i<len替换为heapheap(a);方法中将heap(a, i + 1);更改为heapSort

问题已解决。