Java利用Strategy模式實(shí)現(xiàn)堆排序
將通用算法放入具體類(HeapSorter),并將通用算法必須調(diào)用的方法定義在接口(HeapSorterHandle)中,從這個(gè)接口派生出DoubleHeapSorter并傳給HeapSorter,之后就可以委托這個(gè)接口實(shí)現(xiàn)具體工作了。
1、圖示

2、項(xiàng)目資產(chǎn)

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(防止亂碼)
到此這篇關(guān)于Java利用Strategy模式實(shí)現(xiàn)堆排序的文章就介紹到這了,更多相關(guān)Java 堆排序內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于@SpringBootApplication詳解
這篇文章主要介紹了關(guān)于@SpringBootApplication的使用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-08-08
Exception in thread main java.lang.NoClassDefFoundError錯(cuò)誤解決方
這篇文章主要介紹了Exception in thread main java.lang.NoClassDefFoundError錯(cuò)誤解決方法,需要的朋友可以參考下2016-08-08
Spring?Boot提高開發(fā)效率必備工具lombok使用
這篇文章主要為大家介紹了Spring?Boot提高開發(fā)效率的必備工具lombok使用方法示例及步驟說明,有需要的朋友可以借鑒參考下,希望能夠有所幫助2022-03-03
sql查詢返回值使用map封裝多個(gè)key和value實(shí)例
這篇文章主要介紹了sql查詢返回值使用map封裝多個(gè)key和value實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07
SpringBoot結(jié)合Vue實(shí)現(xiàn)投票系統(tǒng)過程詳解
這篇文章主要介紹了SpringBoot+Vue框架實(shí)現(xiàn)投票功能的項(xiàng)目系統(tǒng),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)吧2022-09-09
Java使用PreparedStatement接口及ResultSet結(jié)果集的方法示例
這篇文章主要介紹了Java使用PreparedStatement接口及ResultSet結(jié)果集的方法,結(jié)合實(shí)例形式分析了PreparedStatement接口及ResultSet結(jié)果集的相關(guān)使用方法與操作注意事項(xiàng),需要的朋友可以參考下2018-07-07

