七种排序算法Java版,最常用的7种
*
* @param array
*/
public static void heapSort(int[] array) {
for (int i = 1; i < array.length; i++) {
makeHeap(array, i);
}
for (int i = array.length - 1; i > 0; i--) {
int temp = array[i];
array[i] = array[0];
array[0] = temp; rebuildHeap(array, i);
}
}
/**
* 堆排序辅助方法---创建堆
* * @param array
* @param k
*/
private static void makeHeap(int[] array, int k) {
int current = k;
while (current > 0 && array[current] > array[(current - 1) / 2]) {
int temp = array[current];
array[current] = array[(current - 1) / 2];
array[(current - 1) / 2] = temp;
current = (current - 1) / 2;
}
}
/**
* 堆排序辅助方法---堆的根元素已删除,末尾元素已移到根位置,开始重建 *
* @param array
* @param size
*/
private static void rebuildHeap(int[] array, int size) { int currentIndex = 0;
int right = currentIndex * 2 + 2;
int left = currentIndex * 2 + 1;
int maxIndex = currentIndex;
boolean isHeap = false;
while (!isHeap) {
if (left < size && array[currentIndex] < array[left]) { maxIndex = left;
}
if (right < size && array[maxIndex] < array[right]) {