建立大根堆,写两个方法,一个sift()调整,一个是堆排序heapSort(),需要注意的是实际排序时要从下标1开始,因为涉及父节点与孩子节点的编号关系,那么从0开始是不合理的
Java
/**
* @author LiuZhiguo
* @date 2019/6/16 15:18
*/
public class HeapSort {
public static void sift(int[] R, int low, int high) {
int i=low, j=2*i;
int temp = R[i];
while (j <= high) {
if (j < high &&R[j] < R[j+1])
++j;
if (temp < R[j]) {
R[i] = R[j];
i = j;
j = 2 * i;
}
else
break;
}
R[i] = temp;
}
public static void heapSort(int R[], int n) {
int i;
int temp;
for (i = n/2;i>=1;--i)
sift(R, i, n-1);
for (i =n-1;i >=2;--i) {
temp = R[1];
R[1] = R[i];
R[i] = temp;
sift(R,1, i-1);
}
}
public static void main(String[] args) {
int[] R = {-1,10,7,2,4,7,62,3,4,2,1,8,9,19};
heapSort(R, R.length);
System.out.println(R);
for (int i=1;i<R.length;i++)
System.out.println(R[i]);
}
}
Python
class HeapSort:
def sift(self, nums, low, high):
i = low
j = 2 * i
temp = nums[i]
while j <= high:
if j < high and nums[j] < nums[j+1]:
j += 1
if nums[j] > temp:
nums[i] = nums[j]
i = j
j = i * 2
else:
break
nums[i] = temp
def heapSort(self, nums):
n = len(nums)
for i in range((n-1)//2, 0, -1):
self.sift(nums, i, n-1)
i -= 1
for i in range(n-1, 0, -1):
temp = nums[i]
nums[i] = nums[1]
nums[1] = temp
self.sift(nums, 1, i-1)
return nums
if __name__ == '__main__':
test = HeapSort()
nums = [-1, 10, 7, 2, 4, 7, 62, 3, 4, 2, 1, 8, 9, 19]
test.heapSort(nums)
print(nums)