标签:pos start span heapsort otto public ret oid 排序
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 }
标签:pos start span heapsort otto public ret oid 排序
原文地址:http://www.cnblogs.com/StringBuilder/p/7464011.html