首页 > 代码库 > 堆排序
堆排序
package com.bupt.acm; import java.util.Scanner; public class HeapSort { private int getLeft(int i){ return 2*(i+1)-1; } private int getRight(int i){ return 2*(i+1); } public void heapSort(int[] numb){ int length=numb.length; int size=length; //根据数组建堆 for(int i=length/2;i>=0;i--){ buildMinHeap(numb,i,size); } //将最小值移到最后元素并调整 int tmp=0; for(int i=size-1;i>=0;i--){ tmp=numb[0]; numb[0]=numb[i]; numb[i]=tmp; buildMinHeap(numb, 0,i); } } private void buildMinHeap(int[] numb,int i,int length){ int largest=i; int left=getLeft(i); int right=getRight(i); if(left<length&&numb[largest]<numb[left]){ largest=left; } if(right<length&&numb[largest]<numb[right]){ largest=right; } if(largest==i){ return; }else{ int tmp=numb[i]; numb[i]=numb[largest]; numb[largest]=tmp; buildMinHeap(numb, largest,length); } } private void buildMaxHeap(int[] numb, int i,int length) { // TODO Auto-generated method stub int largest=i; int left=getLeft(i); int right=getRight(i); if(left<length&&numb[largest]>numb[left]){ largest=left; } if(right<length&&numb[largest]>numb[right]){ largest=right; } if(largest==i){ return; }else{ int tmp=numb[i]; numb[i]=numb[largest]; numb[largest]=tmp; buildMaxHeap(numb, largest,length); } } public static void main(String[] args){ int[] result=null; int n=0; Scanner scanner=new Scanner(System.in); HeapSort heapSort=new HeapSort(); while(scanner.hasNext()){ n=scanner.nextInt(); result=new int[n]; for(int i=0;i<n;i++){ result[i]=scanner.nextInt(); } heapSort.heapSort(result); for (int i = 0; i < result.length; i++) { System.out.print(result[i]+" "); } System.out.println(); } } }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。