Algorithm-Sort-Select-HeapSort01-Java-堆排序

HeapSort

GIF演示:

	public static void heapSort(int[] array) {
		for (int i = 0; i <= array.length - 2; i++) {
			heapAdjust(array, array.length - 1 - i);
			int tmp = array[0];
			array[0] = array[array.length - 1 - i];
			array[array.length - 1 - i] = tmp;
		}
	}
	public static void heapAdjust(int[] array, int lastIndex) {
		for (int i = (lastIndex - 1) / 2; i >= 0; i--) {
			int parentIndex = i;
			while (parentIndex * 2 + 1 <= lastIndex) {
				int childIndex = 2 * parentIndex + 1;
				if (childIndex < lastIndex) {
					if (array[childIndex] < array[childIndex + 1]) {
						childIndex++;
					}
				}
				if (array[parentIndex] < array[childIndex]) {
					int tmp = array[parentIndex];
					array[parentIndex] = array[childIndex];
					array[childIndex] = tmp;
				} else {
					break;
				}
			}
		}
	}

Algorithm-Sort-Select-HeapSort01-Java-堆排序_第1张图片

待改进1:排序分析、时间复杂度和空间复杂度分析

小白发文,有错及不足请指出,嘻嘻?~~~,Learning on the way~~~

你可能感兴趣的:(Algorithm-Sort,Java-Java基础)