今天开始学Java 排序算法之堆排序
2018-03-09 23:06
316 查看
大顶堆用于升序排列:经过多次比较把最大的元素放到根结点(相当于找到序列里面的最大元素),然后再将这个最大元素放到叶结点,这个叶结点就固定不动了,继续比较其它结点,从剩下的结点里面供一个最大元素出来放到根结点,依次循环。
public class InsertSort {
public static void sort(int[] a){
//formulate the bigtoptree
for(int i = a.length/2-1;i>=0;i--){
adjustHeap(a,i,a.length);
}
// change the top to the butten
for(int j =a.length-1;j>0;j--)
{
swap(a,0,j);//将堆顶元素与末尾元素进行交换
adjustHeap(a,0,j);
}
}
public static void adjustHeap(int [] a,int i ,int len){
//adjust the Heap
int tmp=a[i];
//这里不要偷懒写成a.length,不然可能只能得到大顶堆
for(int k=i*2+1;k<len;k=k*2+1){
//if the right Node > the left Node
if(k+1<len &&a[k+1] >a[k] ){
k=k+1;
}
//if the son Node > father Node,let father's valuse equal the son's valuse
if(a[k] >tmp){
a[i] = a[k];
i=k;
}else{break;}
}
a[i] = tmp;
}
public static void swap(int []arr,int a ,int b){
int temp=arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = {4,5,8,1,9,3,0};
sort(a);
for(int i = 0;i<a.length;i++){
System.out.print(a[i]+" ");
}
}
public class InsertSort {
public static void sort(int[] a){
//formulate the bigtoptree
for(int i = a.length/2-1;i>=0;i--){
adjustHeap(a,i,a.length);
}
// change the top to the butten
for(int j =a.length-1;j>0;j--)
{
swap(a,0,j);//将堆顶元素与末尾元素进行交换
adjustHeap(a,0,j);
}
}
public static void adjustHeap(int [] a,int i ,int len){
//adjust the Heap
int tmp=a[i];
//这里不要偷懒写成a.length,不然可能只能得到大顶堆
for(int k=i*2+1;k<len;k=k*2+1){
//if the right Node > the left Node
if(k+1<len &&a[k+1] >a[k] ){
k=k+1;
}
//if the son Node > father Node,let father's valuse equal the son's valuse
if(a[k] >tmp){
a[i] = a[k];
i=k;
}else{break;}
}
a[i] = tmp;
}
public static void swap(int []arr,int a ,int b){
int temp=arr[a];
arr[a] = arr[b];
arr[b] = temp;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = {4,5,8,1,9,3,0};
sort(a);
for(int i = 0;i<a.length;i++){
System.out.print(a[i]+" ");
}
}
相关文章推荐
- 今天开始学Java 排序算法之冒泡排序
- 今天开始学Java 排序算法之简单选择排序
- 今天开始学Java 排序算法之归并排序
- 今天开始起步学软件,写一点文章
- 今天开始备站SCJP
- 写blog,今天开始
- 从今天开始学习设计模式
- 朋友昨天发布的软件,今天就被破解了,郁闷.开始修炼汇编
- 今天开始我的人生
- 就从今天开始吧
- 要开始准备找工作了,昨天闲时就自己写了个数据结构排序类,包括了堆排序,归并排序,速度排序,插入排序。
- 今天开始复习H3C NE
- 今天开始好好管理无忧博客了
- 今天开始使用Eclips
- 今天开始学模式识别与机器学习Pattern Recognition and Machine Learning (PRML)书,章节1.2,Probability Theory (上)
- 今天开始写博客
- 从今天开始记录自己想记录的
- 【小强推歌】---音乐从今天开始
- 今天开始学Python(dictionary的keys,values,items函数)
- 今天卡巴开始封key了,现在分享 整合Kav 6.0(KIS6.0) 一组可用key 至 2008-01-2