Assignment 5: heap sort solve

This commit is contained in:
Yuri Tatishchev 2025-02-24 12:54:41 -08:00
parent f7b209a844
commit afb273d714
Signed by: CaZzzer
GPG Key ID: 28BE602058C08557

View File

@ -4,20 +4,43 @@ import java.io.*;
import java.util.*;
public class Assignment {
public static int[] heapify(int[] heap, int sizeA, int index) {
// Fill in here
// 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) {
// Fill in here
return heapify(arr, sizeA, 1);
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) {
// Fill in here
return buildHeap(arr, 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) {