堆排序
2016-05-14 11:51
441 查看
public class Main{ public static void main(String[] args){ int[] A = {15,45,8,6,7}; int[] answer = heapSort(A); System.out.println("answer:"); for(int i = 0; i < answer.length; ++ i) System.out.print(answer[i] + " "); System.out.println(""); } //keep the max_heap's features public static void maxHeapify(int[] A,int i){ int largest = i; int left = 2 * i; int right = 2 * i + 1; if(left < A.length && A[i] < A[left]) largest = left; if(right < A.length && A[i] < A[right]) largest = right; if(largest != i){ int temp = A[i]; A[i] = A[largest]; A[largest] = temp; maxHeapify(A,largest); } } //create a max_heap public static void buildHeap(int[] A){ for(int i = A.length/2 - 1; i >= 0; --i) maxHeapify(A,i); } //begin to sort public static int[] heapSort(int[] A){ int[] answer = new int[A.length]; buildHeap(A); for(int i = 0; i < A.length - 1; ++i){ answer[i] = A[0]; A[0] = A[A.length - 1 - i]; A[A.length - 1 - i] = -1000000000; maxHeapify(A, 0); } answer[answer.length - 1] = A[0]; return answer; } }
相关文章推荐
- 【Tempest】openstack自动化测试组件tempest及自动化测试工具nose
- linux学习(四):实体链接与符号链接
- 优先队列-堆排序
- 加快eclipse
- 第10、11周项目3 警察和厨师(1)
- Post方式请求网络数据
- 231. Power of Two
- 什么是Node.js
- hdu 3038 How Many Answers Are Wrong
- 51nod 1134 最长递增子序列 nlogn lis
- Spark入门实战系列--5.Hive(上)--Hive介绍及部署
- 系统属性调用评估报告
- wamp环境下配置vhost
- activiti modeler在线编辑器关闭跳转路劲自定义
- Fibonacci
- Java对象的克隆
- 【图文详解】scrapy爬虫与动态页面——爬取拉勾网职位信息(2)
- java构造器小结
- hdu 1087 递增子序列和
- rsync+inotify实时备份加nfs挂载实战