?视频讲解地址:【手把手带你写十大排序】7.堆排序(Java语言)_哔哩哔哩_bilibili
代码:
public class HeapSort {
public void swap(int[] array, int index1, int index2) {
array[index1] = array[index1] ^ array[index2];
array[index2] = array[index1] ^ array[index2];
array[index1] = array[index1] ^ array[index2];
}
public void downAdjust(int[] array, int index, int arrayLength) {
if (index > (arrayLength - 2) >> 1) {
return;
} else if ((index * 2) + 2 >= arrayLength) {
if (array[(index * 2) + 1] > array[index]) {
swap(array, (index * 2) + 1, index);
}
} else {
if (array[(index * 2) + 2] > array[index] && array[(index * 2) + 2] >= array[(index * 2) + 1]) {
swap(array, (index * 2) + 2, index);
downAdjust(array, (index * 2) + 2, arrayLength);
} else if (array[(index * 2) + 1] > array[index] && array[(index * 2) + 1] > array[(index * 2) + 2]) {
swap(array, (index * 2) + 1, index);
downAdjust(array, (index * 2) + 1, arrayLength);
}
}
}
public void initHeap(int[] array, int arrayLength) {
boolean hasTwochild = (arrayLength % 2) == 1 ? true : false;
for (int i = (arrayLength - 2) >> 1; i >= 0; i--) {
if (hasTwochild) {
if (array[(i * 2) + 2] > array[i] && array[(i * 2) + 2] >= array[(i * 2) + 1]) {
swap(array, (i * 2) + 2, i);
downAdjust(array, (i * 2) + 2, arrayLength);
} else if (array[(i * 2) + 1] > array[i] && array[(i * 2) + 1] > array[(i * 2) + 2]) {
swap(array, (i * 2) + 1, i);
downAdjust(array, (i * 2) + 1, arrayLength);
}
} else {
if (array[(i * 2) + 1] > array[i]) {
swap(array, (i * 2) + 1, i);
}
hasTwochild = true;
}
}
}
public void sortFunction(int[] array) {
int arrayLength = array.length;
for (int i = array.length - 1; i > 0; i--) {
initHeap(array, arrayLength);
swap(array, i, 0);
arrayLength--;
}
}
}