经典排序之堆排序
2014-10-04 21:19
274 查看
堆排序,想必大家已经很熟悉,下面贴代码。
输出结果
代码很简单,不过堆排序的思想值得人深思。
public class HeapSort { public void heapSort(int[] a){ for(int i=a.length/2-1;i>=0;i--){ adjustHeap(a,i,a.length);//建堆 } for(int i=a.length-1;i>0;i--){ swap(a, 0, i);//把最大元素放到最后,再次建堆时不参与 adjustHeap(a,0,i);//再次建堆 } } //调整成堆 public void adjustHeap(int[] a,int i,int length){ int child = 0; int max; //从开始元素,从上到下依次进行调整。 for(max=a[i];leftChild(i)<length;i=child){ child=leftChild(i); if(child!=length-1 && a[child]<a[child+1]){ child++; } if(max<a[child]){ a[i]=a[child]; } else break; } a[i]=max; } //左孩子的下标 public int leftChild(int i){ return 2*i+1; } //把最大元素依次放到最后,就是个交换 public void swap(int a[],int start,int max){ int temp=0; temp=a[start]; a[start]=a[max]; a[max]=temp; } //堆排序的测试 public static void main(String[] args){ int a[]={1,10,7,3,6,4,2,8}; HeapSort heapSort=new HeapSort(); heapSort.heapSort(a); for(int i=0;i<a.length;i++){ System.out.println(a[i]); } } }
输出结果
1 2 3 4 6 7 8 10
代码很简单,不过堆排序的思想值得人深思。
相关文章推荐
- 经典排序之堆排序
- 经典排序——堆排序——C语言版
- 数据结构经典排序---堆排序
- 经典排序之 堆排序
- 经典排序之堆排序
- 经典排序之堆排序
- java进阶- 经典排序(插入排序、冒泡排序、快排(分划交换排序)、直接选择排序、堆排序、合并排序)
- 经典排序算法 -----冒泡排序,插入排序,快速排序,归并排序,堆排序
- 经典内部排序: 堆排序,快排,归并排序
- 经典排序之 堆排序
- 【经典】【排序】快速排序算法、堆排序
- 经典排序算法学习笔记五——直接选择排序
- 算法系列15天速成——第一天 七大经典排序【上】
- 新手讲排序:堆排序 和 认识二叉堆
- 排序之堆排序
- 算法分析-选择排序(直接选择排序 & 堆排序)
- 算法系列15天速成——第二天 七大经典排序【中】
- 排序之堆排序
- #Objective-C 经典字典数组排序 - 省市区
- 经典算法——堆排序笔试题