Heap Sort

Description

Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for the remaining elements.

Code


  function heap(arr) {
      start = 0;
      end = arr.length -1 ;
      for(let i=end;i>0;i--) {
          for(let j=Math.floor((i-1)/2);j>=0;j--) {
              let left = 2*j+1;
              let right = 2*j+2;
              let big = left;
              if(right <=i && arr[right]>arr[left]) {
                  big = right;
              }
              if(arr[j] < arr[big]) {
                  let temp = arr[big];
                  arr[big] = arr[j];
                  arr[j] = temp;
              }
          }
          let temp = arr[i];
          arr[i] = arr[0];
          arr[0] = temp;
      }
      return arr;
    }
                    
Complexity
Time Complexity:

Best Case : Ω (n log(n))
Average Case : θ (n log(n))
Worst Case: O (n log(n))

Space Complexity:

O(1)

** where n is the length of the array

To Learn more about Heap Sort, refer the link given below: Heap sort