亲宝软件园·资讯

展开

Java 堆排序

代码骑士 人气:0

将通用算法放入具体类(HeapSorter),并将通用算法必须调用的方法定义在接口(HeapSorterHandle)中,从这个接口派生出DoubleHeapSorter并传给HeapSorter,之后就可以委托这个接口实现具体工作了。

1、图示

2、项目资产

3、源代码

接口类:HeapSortHandle

public interface HeapSorterHandle {
    public void swap(int index);
    public int length();
    public void setArray(Object array);
    public void adjustHeap(int i, int length);
}

接口派生类: DoubleHeapSorter 

public class DoubleHeapSorter implements HeapSorterHandle{
 
    private double[] array = null;
 
    public void swap(int index)
    {
      double temp = array[index];
      array[index] = array[0];
      array[0] = temp;
    }
 
    public int length()
    {
        return array.length;
    }
 
    public void setArray(Object array)
    {
        this.array = (double[])array;
    }
 
    public void adjustHeap(int i, int length) 
    {
        double temp = array[i];
        for(int k=i*2+1;k<length;k=k*2+1)
        {
            if(k+1<length && array[k]<array[k+1])
            {
                k++;
            }
            if(array[k] >temp)
            {
                array[i] = array[k];
                i = k;
            }
            else
            {
                break;
            }
        }
        array[i] = temp;
    }
    
}

具体算法类 HeapSorter :

public class HeapSorter {
    private int length = 0;
    private HeapSorterHandle itsSortHandle = null;
 
    public HeapSorter(HeapSorterHandle handle)
    {
        itsSortHandle = handle;
    }
 
    public void Sort(Object array)
    {
        itsSortHandle.setArray(array);
        length = itsSortHandle.length();
        if (length <= 1) return;
        for(int i=length/2-1;i>=0;i--)
        {
            itsSortHandle.adjustHeap(i,length);
        }
        for(int j=length-1;j>0;j--)
        {
            itsSortHandle.swap(j);
            itsSortHandle.adjustHeap(0,j);
        }
        return;
    }
}

主类Main:

import java.util.Arrays;
 
public class Main {
    public static void main(String[] args)
      {
          HeapSorter HS = new HeapSorter(new DoubleHeapSorter());
          double []array = {1,5,2,3,4,6,7};
          System.out.println("堆排序前:"+Arrays.toString(array));
          HS.Sort(array);
          System.out.println("堆排序后:"+Arrays.toString(array));
      }
}

输出:

注:javac -encoding UTF-8 Main.java(防止乱码) 

加载全部内容

相关教程
猜你喜欢
用户评论