heapsort in PriorityQueue

来源:互联网 发布:搜狐动态ip软件 编辑:程序博客网 时间:2024/06/13 07:48

先上图:


size = 8

Pi = (Ci+1)/2-1

CLi  = 2Pi+1

CRi = CLi+1

备注:Pi为父节点index

           Ci为子节点index

          CLi为左子节点index

          CRi为右子节点index


PriorityQueue中的数据结构为:

Object[] queue ,是一个数组,如上图所示是以个数组实现的完全二叉树


关键代码:


heapify 为将一个无序的数组变为有序



private void heapify() {        for (int i = (size >>> 1) - 1; i >= 0; i--)            siftDown(i, (E) queue[i]);    }private void siftDown(int k, E x) {        int half = size >>> 1;        while (k < half) {            int child = (k << 1) + 1;            Object c = queue[child];            int right = child + 1;            if (right < size &&                comparator.compare((E) c, (E) queue[right]) > 0)                c = queue[child = right];            if (comparator.compare(x, (E) c) <= 0)                break;            queue[k] = c;            k = child;        }        queue[k] = x;    }

remove的模块为:

 E removeAt(int i) {        // assert i >= 0 && i < size;        modCount++;        int s = --size;        if (s == i) // removed last element            queue[i] = null;        else {            E moved = (E) queue[s];            queue[s] = null;            siftDown(i, moved);            if (queue[i] == moved) {                siftUp(i, moved);                if (queue[i] != moved)                    return moved;            }        }        return null;    }private void siftUp(int k, E x) {        while (k > 0) {            int parent = (k - 1) >>> 1;            Object e = queue[parent];            if (comparator.compare(x, (E) e) >= 0)                break;            queue[k] = e;            k = parent;        }        queue[k] = x;    }

add模块为:

 public boolean offer(E e) {        if (e == null)            throw new NullPointerException();        modCount++;        int i = size;        if (i >= queue.length)            grow(i + 1);        size = i + 1;        if (i == 0)            queue[0] = e;        else            siftUp(i, e);        return true;    }





原创粉丝点击