From dd369b451a24ed62d31007b1ec4b35a730c73b2f Mon Sep 17 00:00:00 2001 From: Kruti Shah Date: Thu, 20 Feb 2025 02:03:06 +0530 Subject: [PATCH] heap implementation --- .../hithomelabs/princeton1/module8/Heap.java | 17 ++++++++++++++--- .../princeton1/module8/HeapSort.java | 8 +++++++- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/module8/src/main/java/com/hithomelabs/princeton1/module8/Heap.java b/module8/src/main/java/com/hithomelabs/princeton1/module8/Heap.java index b728767..f439091 100644 --- a/module8/src/main/java/com/hithomelabs/princeton1/module8/Heap.java +++ b/module8/src/main/java/com/hithomelabs/princeton1/module8/Heap.java @@ -14,10 +14,23 @@ public class Heap{ * * Implement sink API to sink a node if it's sub-heap is not heap-order */ public static void sink(T[] arr, int root, int N){ + while (N >= root*2) { + int greater_index = root * 2; + if (N >= root * 2 + 1 && less(arr[root * 2], arr[root * 2 + 1])) + greater_index += 1; + if(!less(arr[root], arr[greater_index])) + break; + exch(arr, root, greater_index); + root = greater_index; + } } // * * Swim if element is not root, and parent is lesser than node - public static > void swim(T[] arr, int node, int N){ + public static void swim(T[] arr, int node){ + while(node > 1 && less(arr[node/2], arr[node])){ + exch(arr, node, node/2); + node = node/2; + } } private static void exch(T[] arr, int i, int j){ @@ -30,6 +43,4 @@ public class Heap{ if(((Comparable)v).compareTo(w) < 1 ) return true; else return false; } - - } diff --git a/module8/src/main/java/com/hithomelabs/princeton1/module8/HeapSort.java b/module8/src/main/java/com/hithomelabs/princeton1/module8/HeapSort.java index 55d7b91..b4ec4e0 100644 --- a/module8/src/main/java/com/hithomelabs/princeton1/module8/HeapSort.java +++ b/module8/src/main/java/com/hithomelabs/princeton1/module8/HeapSort.java @@ -2,7 +2,6 @@ package com.hithomelabs.princeton1.module8; import com.hithomelabs.princeton1.module5.AbstractCustomSorts; - public class HeapSort extends AbstractCustomSorts { @Override @@ -23,5 +22,12 @@ public class HeapSort extends AbstractCustomSorts { * * P.S the provision of making the index 0 null for ease of use has already been done above */ private void coreSortingLogic(E[] arr, int N) { + for(int n=2; n <= N; n++){ + Heap.swim(arr, n); + } + while (N > 1){ + exch(arr, 1, N--); + Heap.sink(arr, 1, N); + } } }