資源描述:
《java排序算法大全.doc》由會員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在行業(yè)資料-天天文庫。
1、java排序算法大全為了便于管理,先引入個基礎(chǔ)類:package?algorithms;public?abstract?class?Sorter>?{????????public?abstract?void?sort(E[]?array,int?from?,int?len);????????public?final?void?sort(E[]?array)????{????????sort(array,0,array.length);????}????protected?final?void?swap(E[]?array,int
2、?from?,int?to)????{????????E?tmp=array[from];????????array[from]=array[to];????????array[to]=tmp;????}}一插入排序該算法在數(shù)據(jù)規(guī)模小的時候十分高效,該算法每次插入第K+1到前K個有序數(shù)組中一個合適位置,K從0開始到N-1,從而完成排序:package?algorithms;/**?*?@author?yovn?*/public?class?InsertSorter>?extends?Sorter?{????public?v
3、oid?sort(E[]?array,?int?from,?int?len)?{?????????E?tmp=null;??????????for(int?i=from+1;ifrom;j--)??????????????{??????????????????if(tmp.compareTo(array[j-1])<0)??????????????????{????????????????
4、??????array[j]=array[j-1];??????????????????}??????????????????else?break;??????????????}??????????????array[j]=tmp;??????????}????}????????????}二冒泡排序這可能是最簡單的排序算法了,算法思想是每次從數(shù)組末端開始比較相鄰兩元素,把第i小的冒泡到數(shù)組的第i個位置。i從0一直到N-1從而完成排序。(當(dāng)然也可以從數(shù)組開始端開始比較相鄰兩元素,把第i大的冒泡到數(shù)組的第N-i個位置。i從0一直到N-1從而完成排序。)package?algori
5、thms;/**?*?@author?yovn?*?*/public?class?BubbleSorter>?extends?Sorter?{????private?static??boolean?DWON=true;????????public?final?void?bubble_down(E[]?array,?int?from,?int?len)????{????????for(int?i=from;ii
6、;j--)????????????{????????????????if(array[j].compareTo(array[j-1])<0)????????????????{????????????????????swap(array,j-1,j);????????????????}????????????}????????}????}????????public?final?void?bubble_up(E[]?array,?int?from,?int?len)????{????????for(int?i=from+len-1;i>=from;i--)????????{??
7、??????????for(int?j=from;j0)????????????????{????????????????????swap(array,j,j+1);????????????????}????????????}????????}????}????@Override????public?void?sort(E[]?array,?int?from,?in