堆排序
Posted StringBuilder
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了堆排序相关的知识,希望对你有一定的参考价值。
1 public class Solution 2 { 3 public void heapSort(int[] data) 4 { 5 heapBuild(data); 6 7 for(int i = data.length - 1; i > 0; i --) 8 { 9 exchange(data, i, 0); 10 11 heapAdjust(data, 0, i - 1); 12 } 13 } 14 15 public void heapBuild(int[] data) 16 { 17 for(int i = (data.length + 1) / 2 - 1; i >= 0; i --) 18 { 19 heapAdjust(data, i, data.length - 1); 20 } 21 } 22 23 public void heapAdjust(int[] data, int startPosition, int bottomPosition) 24 { 25 if(startPosition > (bottomPosition + 1) / 2 - 1) 26 { 27 return; 28 } 29 30 int leftChildIndex = 2 * startPosition + 1; 31 32 int rightChildIndex = 2 * startPosition + 2; 33 34 int maxValueIndex = startPosition; 35 36 if(data[leftChildIndex] > data[maxValueIndex]) 37 { 38 maxValueIndex = leftChildIndex; 39 } 40 41 if(rightChildIndex <= bottomPosition) 42 { 43 if(data[rightChildIndex] > data[maxValueIndex]) 44 { 45 maxValueIndex = rightChildIndex; 46 } 47 } 48 49 if(maxValueIndex != startPosition) 50 { 51 exchange(data, maxValueIndex, startPosition); 52 53 heapAdjust(data, maxValueIndex, bottomPosition); 54 } 55 } 56 57 public void exchange(int[] data, int m, int n) 58 { 59 int memory = data[m]; 60 61 data[m] = data[n]; 62 63 data[n] = memory; 64 } 65 66 }
以上是关于堆排序的主要内容,如果未能解决你的问题,请参考以下文章