cs146/05-labHeapSort/Assignment.java

66 lines
2.0 KiB
Java

package labHeapSort;
import java.io.*;
import java.util.*;
public class Assignment {
public static int[] heapify(int[] heap, int sizeA, int index) {
// check parent and children to find the largest node
int largest = index;
int left = 2 * index + 1;
int right = 2 * index + 2;
if (left < sizeA && heap[left] > heap[largest]) largest = left;
if (right < sizeA && heap[right] > heap[largest]) largest = right;
// if largest isn't the parent, swap with the largest child and recursively heapify
if (largest != index) {
final int tmp = heap[index];
heap[index] = heap[largest];
heap[largest] = tmp;
return heapify(heap, sizeA, largest);
}
return heap;
}
public static int[] buildHeap(int[] arr, int sizeA) {
for (int i = sizeA / 2; i > 0; i--) {
heapify(arr, sizeA, i);
}
return heapify(arr, sizeA, 0);
}
public static int[] heapSort(int[] arr, int sizeA) {
arr = buildHeap(arr, sizeA);
// for each element
for (int i = 1; i < sizeA; i++) {
// swap heap top (largest element) with the last array element and reheapify
int top = arr[0];
arr[0] = arr[sizeA - i];
arr[sizeA - i] = top;
arr = heapify(arr, sizeA - i, 0);
}
return arr;
}
public static void run(String inputPath) {
try (BufferedReader br = new BufferedReader(new FileReader(inputPath))) {
int size = Integer.parseInt(br.readLine());
int[] A = new int[size];
for (int i = 0; i < size; i++) {
A[i] = Integer.parseInt(br.readLine());
}
int[] heap = heapSort(A, size);
for (int i = 0; i < size; i++) {
System.out.print(heap[i] + ";");
}
System.out.println();
} catch (IOException e) {
e.printStackTrace();
}
}
}