首页 > 代码库 > java语言实现堆排序
java语言实现堆排序
package secondChapter; import java.util.Random; public class HeapSort { private static int AHeapSize; public static void main(String[] args) { HeapSort hs = new HeapSort(); int[] A = new int[10]; //产生随机数组 for(int i=0;i<A.length;i++){ A[i] = hs.generateRandomInt(50); } System.out.print("Original array:"); for (int i = 0; i < A.length; i++) { System.out.print(A[i]+" "); } System.out.println(); hs.heap_sort(A); System.out.print("Sorted array: "); for (int i = 0; i < A.length; i++) { System.out.print(A[i]+" "); } } //HEAPSORT过程 public void heap_sort(int[] A) { AHeapSize = A.length; build_max_heap(A); System.out.print("build_max_heap: "); for (int i = 0; i < A.length; i++) { System.out.print(A[i]+" "); } System.out.println(); for(int i=A.length;i>1;i--){ int temp = A[0]; A[0] = A[i-1]; A[i-1] = temp; AHeapSize -= 1; max_heapify(A,1); } } //HUILD-MAX-HEAP过程 public void build_max_heap(int[] A) { for(int i=A.length/2;i>0;i--){ max_heapify(A,i); } } //MAX-HEAPIFY过程 public void max_heapify(int[] A, int i) { //i为 元素下标+1 int l = 2*i; int r = 2*i+1; int largest; if(l<=AHeapSize && A[l-1]>A[i-1]){ largest = l; }else{ largest = i; } if(r<=AHeapSize && A[r-1]>A[largest-1]){ largest = r; } if(largest!=i){ int temp = A[i-1]; A[i-1] = A[largest-1]; A[largest-1] = temp; max_heapify(A, largest); } } private Random rd = new Random(); public int generateRandomInt(int bound) { return rd.nextInt(bound); } }
输出结果:
Original array:40 44 11 43 25 0 7 14 34 14
build_max_heap: 44 43 11 40 25 0 7 14 34 14
Sorted array: 0 7 11 14 14 25 34 40 43 44
java语言实现堆排序
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。