DEV Community

Debesh P.
Debesh P.

Posted on

2 2 1 1 1

Heap Sort Algorithm | Heapify | GeeksforGeeks Beginner's DSA Sheet | Heap Tree

hola coders!

In this video, I solve a Heap Sort problem from GeeksforGee. If you’ve ever struggled with Heap Sort, this is the perfect hands-on example to help you understand how it works in real coding scenarios.

what’s in this video?

  • Quick explanation of Heap Sort & Heapify
  • Live problem-solving from GeeksforGeeks
  • Writing clean & efficient code
  • Analyzing time complexity

Problem Link: https://www.geeksforgeeks.org/problems/heap-sort/1
Solution Link: https://github.com/debeshp6/Gfg-Tutorials


Code

class Solution {
    // Function to sort an array using Heap Sort.
    public void heapSort(int arr[]) {
        // code here
        int n = arr.length;
        for(int i=n/2-1; i>=0; i--) {
            heapify(arr,n,i);
        }

        for(int i=n-1; i>0; i--) {
            int temp = arr[0];
            arr[0] = arr[i];
            arr[i] = temp;

            heapify(arr,i,0);
        }
    }

    public void heapify(int[] arr, int n, int i) {
        int largest = i;
        int left = 2*i+1;
        int right = 2*i+2;

        if(left < n && arr[left] > arr[largest]) {
            largest = left;
        }

        if(right < n && arr[right] > arr[largest]) {
            largest = right;
        }

        if(largest != i) {
            int temp = arr[largest];
            arr[largest] = arr[i];
            arr[i] = temp;

            heapify(arr, n, largest);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Time Complexity: O(nlogn)


if you're preparing for coding interviews or competitive programming, Heap Sort is a must-know algorithm, and this problem will strengthen your grasp on it!

Heroku

Built for developers, by developers.

Whether you're building a simple prototype or a business-critical product, Heroku's fully-managed platform gives you the simplest path to delivering apps quickly — using the tools and languages you already love!

Learn More

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Generate and update README files, create data-flow diagrams, and keep your project fully documented. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

If this post resonated with you, feel free to hit ❤️ or leave a quick comment to share your thoughts!

Okay