目录
- 1、图示
- 2、项目资产
- 3、源代码
将通用算法放入具体类(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(防止乱码)
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

评论(0)