Data Structures and Algorithms abbreviated - stack and heap sort

stack


concept

  • Heap is a complete binary tree;
  • Value for each node of the heap must value for each node in the subtree which is greater than or equal to (or less).
  • Depending on the size relationship between the child node with the value of the tree is divided into: large and small roof top heap heap.

How to achieve

  • How to store
    • Binary tree complete binary tree sections have talked about for a storage array, so use an array to store the heap
  • What operation
    • Inserting an element (O (logN)) - is inserted into the end of the array is performed from the bottom up stacks of : up along the path to the top of the stack, one by one from the comparison is not satisfied exchanged, the ends meet.
    • public class Heap {
        private int [] a; // array data storage begins at index 1
        private int n; // stack the maximum number of data that can be stored
        // the number of data already stored in the stack; private int count
      
        public Heap(int capacity) {
          a = new int[capacity + 1];
          n = capacity;
          count = 0;
        }
      
        public void insert(int data) {
          if (count> = n) return; // filled
          ++count;
          a[count] = data;
          int i = count;
          while (i / 2> 0 && a [i]> a [i / 2]) {// from bottom to top of the stack
            swap (a, i, i / 2); // swap () function operates: the subscript i and exchanging two elements i / 2
            i = i/2;
          }
        }
       }
      
    • Delete the top of the heap element (O (logN)) - we put the last node onto the top of the heap, and then use the same method of comparing parent and child nodes. Parent-child relationship is not satisfied for the size, interchanged, two nodes, and this process is repeated, until satisfied until the magnitude relation between parent and child nodes. This is from the top of the heap method .
    • public void removeMax() {
        if (count == 0) return -1; // no data stack
        a[1] = a[count];
        --count;
        heapify(a, count, 1);
      }
      
      private void heapify (int [] a, int n, int i) {// down from the top of the stack
        while (true) {
          int maxPos = i;
          if (i*2 <= n && a[i] < a[i*2]) maxPos = i*2;
          if (i*2+1 <= n && a[maxPos] < a[i*2+1]) maxPos = i*2+1;
          if (maxPos == i) break;
          swap(a, i, maxPos);
          i = maxPos;
        }
      }
      

How to achieve a heap-based sort?

 

 

Guess you like

Origin www.cnblogs.com/wod-Y/p/12032665.html
Recommended