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!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Heroku

Tired of jumping between terminals, dashboards, and code?

Check out this demo showcasing how tools like Cursor can connect to Heroku through the MCP, letting you trigger actions like deployments, scaling, or provisioning—all without leaving your editor.

Learn More

👋 Kindness is contagious

Dive into this thoughtful piece, beloved in the supportive DEV Community. Coders of every background are invited to share and elevate our collective know-how.

A sincere "thank you" can brighten someone's day—leave your appreciation below!

On DEV, sharing knowledge smooths our journey and tightens our community bonds. Enjoyed this? A quick thank you to the author is hugely appreciated.

Okay