Skip to content

Commit

Permalink
堆的replace 和 heapify 的实现
Browse files Browse the repository at this point in the history
  • Loading branch information
Xikl committed Jan 5, 2019
1 parent 3a91e37 commit bc97b20
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package com.ximo.datastructuresinaction.array;

import java.util.Arrays;

/**
* 自己的一个数组类
*
Expand All @@ -23,6 +25,12 @@ public Array(int capacity) {
size = 0;
}

@SuppressWarnings("unchecked")
public Array(E[] arr) {
data = (E[])Arrays.stream(arr).toArray();
size = arr.length;
}

public Array() {
this(10);
}
Expand Down
31 changes: 31 additions & 0 deletions src/main/java/com/ximo/datastructuresinaction/heap/MaxHeap.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,21 @@ public MaxHeap() {
data = new Array<>();
}

/**
* 找到最后一个叶子节点,然后找到他的父亲节点
*
*
*
* @param arr
*/
public MaxHeap(E[] arr) {
data = new Array<>(arr);
// 找到最后一个叶子节点,然后找到他的父亲节点
for (int cur = getParentIndex(arr.length - 1); cur >= 0; cur--) {
siftDown(cur);
}
}

public int size() {
return data.getSize();
}
Expand Down Expand Up @@ -111,5 +126,21 @@ public int getMaxOnLeftAndRightValueIndex(int index) {
return leftLessThanRight ? rightChildIndex : leftChildIndex;
}

/**
* 取出堆中最大的元素,并替换为新的元素
* 再进行下沉操作
*
* @param newValue 一个新的值
* @return 堆中的最大值
*/
public E replace(E newValue) {
E max = findMax();
data.set(0, newValue);
siftDown(0);
return max;
}




}
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
package com.ximo.datastructuresinaction.array;

import com.ximo.datastructuresinaction.array.Array;
import org.junit.Test;

/**
Expand All @@ -25,4 +24,10 @@ public void testToString() {
// System.out.println(arr.toString());
}

@Test
public void testArrToMyArray() {
Integer[] arr = {1, 2, 3};
Array<Integer> array = new Array<>(arr);
System.out.println(array);
}
}

0 comments on commit bc97b20

Please sign in to comment.