Python 官方文档:入门教程 => 点击学习
目录1、图示2、项目资产3、源代码将通用算法放入具体类(HeapSorter),并将通用算法必须调用的方法定义在接口(HeapSorterHandle)中,从这个接口派生出Doubl
将通用算法放入具体类(HeapSorter),并将通用算法必须调用的方法定义在接口(HeapSorterHandle)中,从这个接口派生出DoubleHeapSorter并传给HeapSorter,之后就可以委托这个接口实现具体工作了。
接口类: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(防止乱码)
到此这篇关于Java利用Strategy模式实现堆排序的文章就介绍到这了,更多相关Java 堆排序内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: Java利用Strategy模式实现堆排序
本文链接: https://lsjlt.com/news/168587.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-03-01
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0