赞
踩
/** * * 1 * 2 3 * 4 5 6 7 *永远去第一个进行访问 访问过后将访问次数+1,然后从新排序 * 排序方式: * 永远之和当前节点的两个子节点进行比较, * 如果访问次数大于左边、小于右边,就和左边的交换位置 * 如果访问次数大于左边也大于右边,那么就和右边交换位置, * */ public class LC { Node[] nodes = null; public void init(String names) { String[] split = names.split(","); nodes = new Node[split.length+1]; for (int i = 0; i < split.length; i++) { Node node = new Node(split[i]);; nodes[i+1] = node; } } public void request(){ System.out.println("before:"+Arrays.toString(nodes)); Node node = nodes[1]; node.num.incrementAndGet(); int i = 1; //如果没有下一层就不用在比较了 i << 1表示当前节点的下一个左节点 while (i << 1 < nodes.length) { int flag = i; int left = 1<<i; int right = left+1; if (nodes[left].num.get() < nodes[flag].num.get()) { flag = left; } if (right < nodes.length && nodes[right].num.get() < nodes[flag].num.get()) { flag = right; } if (i != flag) { Node temp = nodes[i]; nodes[i] = nodes[flag]; nodes[flag] = temp; i = flag; }else { break; } } System.out.println("after:"+ Arrays.toString(nodes)); System.out.println("=========================="); } public static void main(String[] args) { LC lc = new LC(); lc.init("a,b,c,d,e"); for (int i = 0; i < 10; i++) { lc.request(); } } class Node{ String name; AtomicInteger num = new AtomicInteger(); public Node(String name) { this.name = name; } @Override public String toString() { return "Node{" + "name='" + name + '\'' + ", num=" + num + '}'; } } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。