Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

heap sort

function heap_root(input, i) {
  /* to create MAX  array */  
    var left = 2 * i + 1;
    var right = 2 * i + 2;
    var max = i;
  // if left child is larger than root
    if (left < array_length && input[left] > input[max]) {
        max = left;
    }
  // if right child is larger than max
    if (right < array_length && input[right] > input[max])     {
        max = right;
    }
  // if max is not root
    if (max != i) {
        swap(input, i, max);
        heap_root(input, max);
    }
}

function swap(input, index_A, index_B) {
    var temp = input[index_A];

    input[index_A] = input[index_B];
    input[index_B] = temp;
}

function heapSort(input) {
    
    array_length = input.length;
  // Building the heap 
    for (var i = Math.floor(array_length / 2); i >= 0; i -= 1)      {
        heap_root(input, i);
      }
  // One by one extract and put in place
    for (i = input.length - 1; i > 0; i--) {
        swap(input, 0, i);
        array_length--;
      
        heap_root(input, 0);
    }
}
Source by sorting-algorithms.me #
 
PREVIOUS NEXT
Tagged: #heap #sort
ADD COMMENT
Topic
Name
2+7 =