GIF demonstration
Source code demonstration
import java.util.Arrays;
public class code03_HeapSort {
public static void main(String[] args) {
int[] array = generateRandomArray(100, 100);
int[] test = copyArray(array);
Arrays.sort(test);
heapSort(array);
compareArray(array, test);
}
public static void heapSort(int[] array) {
if (array == null || array.length < 2) {
return;
}
int heapSize = array.length;
for (int i = 0; i < array.length; i++) {
heapInsert(array, i);
}
swap(array, 0, --heapSize);
while (heapSize > 0) {
heapify(array, 0, heapSize);
swap(array, 0, --heapSize);
}
}
public static void heapInsert(int[] array, int index) {
while (array[index] > array[(index - 1) / 2]) {
swap(array, index, (index - 1) / 2);
index = (index - 1) / 2;
}
}
public static void heapify(int[] array, int index, int heapSize) {
int left = (2 * index) + 1;
while (left < heapSize) {
int largest = (left + 1 < heapSize && array[left + 1] > array[left]) ? left + 1 : left;
largest = array[largest] > array[index] ? largest : index;
if (largest == index) {
break;
}
swap(array, largest, index);
index = largest;
left = (2 * index) + 1;
}
}
public static void swap(int[] array, int i, int j) {
if (i == j) {
return;
}
array[i] = array[i] ^ array[j];
array[j] = array[i] ^ array[j];
array[i] = array[i] ^ array[j];
}
public static int[] generateRandomArray(int maxSize, int maxValue) {
int[] array = new int[(int) ((maxSize + 1) * Math.random())];
for (int i = 0; i < array.length; i++) {
array[i] = (int) (maxValue * Math.random());
}
return array;
}
public static void compareArray(int[] array1, int[] array2) {
if (!Arrays.equals(array1, array2)) {
System.out.println("No equals!!");
} else {
System.out.println("Success!!");
}
}
public static int[] copyArray(int[] array) {
int[] tmp = new int[array.length];
System.arraycopy(array, 0, tmp, 0, array.length);
return tmp;
}
}