();
+ queue.offer(root);
+ while (!queue.isEmpty()) {
+ Node cur = queue.poll();
+ System.out.print(cur.data + " ");
+ if (cur.left != null) {
+ queue.offer(cur.left);
+ }
+ if (cur.right != null) {
+ queue.offer(cur.right);
+ }
+ }
+ }
+ }
+
+ /**
+ * 统计树的节点数
+ *
+ * @param root
+ */
+ public static int getNodes(Node root) {
+ if (root == null) {
+ return 0;
+ }
+ return getNodes(root.left) + getNodes(root.right) + 1;
+ }
+
+ /**
+ * 得到树的叶子节点的数目
+ * @param root
+ * @return
+ */
+ public static int getLeafs(Node root) {
+ if (root == null) {
+ return 0;
+ }
+ if (root.right == null && root.left == null) {
+ return 1;
+ }
+ return getLeafs(root.left) + getLeafs(root.right);
+
+ }
+
+
+ /**
+ * 计算树的深度
+ * @param root
+ * @return
+ */
+ public static int getHeight(Node root){
+ if (root == null) {
+ return 0;
+ }
+ int leftHeight = getHeight(root.left) + 1;
+ int rightHeight = getHeight(root.right) + 1;
+ return leftHeight> rightHeight ? leftHeight : rightHeight;
+ }
+
+ /**
+ * 计算第K层的节点数
+ * @param root
+ * @param k
+ * @return
+ */
+ public static int calcKNodes(Node root, int k) {
+ if (root == null || k < 0) { + return 0; + } + if (k == 0){ + return 1; + } + return calcKNodes(root.left, k - 1) + calcKNodes(root.right, k - 1); + + } + + /** + * 判断两个树的结构是否相同 + * @param root1 + * @param root2 + * @return + */ + public static boolean isCommon(Node root1, Node root2) { + if (root1 == null && root2 == null) { + return true; + } else if (root1 == null || root2 == null) { + return false; + }else{ + boolean isLeftCommon = isCommon(root1.left, root2.left); + boolean isRightCommon = isCommon(root1.right, root2.right); + return isLeftCommon && isRightCommon; + } + } + + /** + * 得到树的镜像,即对于每一个节点,交换他们的左右孩子节点。 + * @param root + */ + public static void mirror(Node root) { + if (root != null) { + Node tmp = root.left; + root.left = root.right; + root.right = tmp; + mirror(root.left); + mirror(root.right); + } + } + + /** + * 得到两个节点的最近公共祖先节点。 + * 递归左右子树,如果返回的值都不为空,则表示在左右子树各找到一个target,因为最近的祖先就是cur + * 如果有一个为空,则就不为空就是最近公共祖先。 + * @param root + * @param target1 + * @param target2 + * @return + */ + public static Node findLCA(Node root, Node target1, Node target2) { + if (root == null) + return null; + + if (root == target1 || root == target2) { + return root; + } + Node left = findLCA(root.left, target1, target2); + Node right = findLCA(root.right, target1, target2); + if (left != null && right != null) { + return root; + } + return left != null ? left:right; + } + + + + public static class Node { + public int data; + public Node left; + public Node right; + + + public Node(int data) { + this.data = data; + left = null; + right = null; + } + } + + +} diff --git a/src/main/java/cn/byhieg/algorithmtutorial/Find.java b/src/main/java/cn/byhieg/algorithmtutorial/Find.java new file mode 100644 index 0000000..f476fb3 --- /dev/null +++ b/src/main/java/cn/byhieg/algorithmtutorial/Find.java @@ -0,0 +1,83 @@ +package cn.byhieg.algorithmtutorial; + +/** + * Created by shiqifeng on 2017/3/29. + * Mail byhieg@gmail.com + */ +public class Find { + + + /** + * 二查查找算法,要求准确找到目标值,没有找到则是-1. + * 此方法保证在相同元素都满足条件时,取到的是最大的下标 + * 时间复杂度 o(lgN) + * @param nums int型数组,要求有序 + * @return 找到,返回下标,没找到,返回-1 + */ + public int binarySearchFind(int[] nums,int des) { + int length = nums.length; + int low = 0; + int high = length - 1; + while (low <= high) { + int mid = (low + high) / 2; + if (nums[mid] == des) { + return mid; + } else if (nums[mid] < des) { + low = mid + 1; + } else{ + high = mid - 1; + } + } + return -1; + } + + /** + * 给定一个单调不降的数组,查找大于des条件的最小的数 + * @param nums + * @param des + * @return + */ + public int binarySearchMinFind(int[] nums, int des) { + int length = nums.length; + int low = 0; + int high = length - 1; + int mid ; + while (low < high) { + mid = (low + high) / 2; + if (nums[mid] <= des){ + low = mid + 1; + }else{ + high = mid; + } + } + if (nums[high]> des) return high;
+ return -1;
+ }
+
+ /**
+ * 给定一个单调不降的数组,查找小于des条件的最大的数
+ * @param nums
+ * @param des
+ * @return
+ */
+ public int binarySearchMaxFind(int[] nums, int des) {
+ int length = nums.length;
+ int low = 0;
+ int high = length - 1;
+ int mid;
+ int result = -1;
+ while (low < high) { + mid = low + (high - low + 1) / 2; + if (nums[mid] < des){ + low = mid; + }else{ + high = mid - 1; + } + } + if (nums[low] < des) return low; + return -1; + } + + + +} diff --git a/src/main/java/cn/byhieg/algorithmtutorial/GraphMatrix.java b/src/main/java/cn/byhieg/algorithmtutorial/GraphMatrix.java new file mode 100644 index 0000000..c22fec3 --- /dev/null +++ b/src/main/java/cn/byhieg/algorithmtutorial/GraphMatrix.java @@ -0,0 +1,166 @@ +package cn.byhieg.algorithmtutorial; + +import java.util.*; + +/** + * Created by shiqifeng on 2017/4/5. + * Mail byhieg@gmail.com + */ +public class GraphMatrix { + + Weight[][] graph; + boolean[] isVisited; + + private static final int UNREACH = Integer.MAX_VALUE>> 1;
+
+ public GraphMatrix(Weight[][] graph) {
+ this.graph = graph;
+ }
+
+ /**
+ * 图的BFS,算法流程
+ * 1. 首先将begin节点入队
+ * 2. 然后判断队列是否为空,不为空,则出队一个元素,输出。
+ * 3. 将出队的元素的所有相邻的元素且没有访问的都放进队列中,重复第二步
+ *
+ * 广度优先遍历,从V0出发,访问V0的各个未曾访问的邻接点W1,W2,...,Wk;然后,依次从W1,W2,...,Wk出发访问各自未被访问的邻接点;
+ *
+ * @param begin
+ */
+ public void BFS(Integer begin) {
+ isVisited = new boolean[graph.length];
+ for (int i = 0; i < isVisited.length; i++) { + isVisited[i] = false; + } + + Queue queue = new LinkedList();
+ queue.offer(begin);
+ isVisited[begin] = true;
+
+ while (!queue.isEmpty()) {
+ int current = queue.poll();
+ System.out.print(current + "-->");
+ for (int i = 0; i < graph[current].length; i++) { + if (i == begin) { + continue; + } + if (graph[current][i].weight != UNREACH && !isVisited[i]) { + queue.offer(i); + isVisited[i] = true; + } + } + } + System.out.println("结束"); + } + + + /** + * 图的DFS算法,算法流程 + * 1. 从begin节点出发,输出begin节点。 + * 2. 循环遍历所有与begin节点相邻并且没有被访问的节点 + * 3. 找到一个节点,就以他为begin,递归调用DFS + * + * @param begin + */ + public void DFS(Integer begin) { + isVisited = new boolean[graph.length]; + for (int i = 0; i < isVisited.length; i++) { + isVisited[i] = false; + } + doDFS(begin); + System.out.println("结束"); + } + + /** + * 假设给定图G的初态是所有顶点均未曾访问过。 + * 在G中任选一顶点v为初始出发点(源点),则深度优先遍历可定义如下: + * 首先访问出发点v,并将其标记为已访问过;然后依次从v出发搜索v的每个邻接点w。 + * 若w未曾访问过,则以w为新的出发点继续进行深度优先遍历,直至图中所有和源点v有路径相通的顶点(亦称为从源点可达的顶点)均已被访问为止。 + * 若此时图中仍有未访问的顶点,则另选一个尚未访问的顶点作为新的源点重复上述过程,直至图中所有顶点均已被访问为止。 + * + * @param begin + */ + private void doDFS(Integer begin) { + isVisited[begin] = true; + System.out.print(begin + "-->");
+ for (int i = 0; i < graph[begin].length; i++) { + if (graph[begin][i].weight != UNREACH && !isVisited[i]) { + doDFS(i); + } + } + } + + /** + * dijkstra 从指定起点到指定终点的最短路 + * paths变量,key为节点,value为start到key节点的最短路径 + * values变量,key为节点,value为start到key节点的最小值 + * 1. dijkstra的核心思想,是广义搜索,先遍历所有与start相邻的节点,且没有找过的点 + * 2. 找出最短的节点k,然后以最短的节点为中间节点,如果start-k-i的距离短于start-i,则修改start到i的值,并且修改start到i的路径 + * 3. 然后在此基础上,继续从start节点去没有找过的点,重复1 + * @param start + * @param end + */ + public void dijkstra(int start, int end) { + + + int n = graph.length; + isVisited = new boolean[n]; + for (int i = 0; i < n; i++) { + isVisited[i] = false; + } + isVisited[start] = true; + HashMap paths = new HashMap();
+ HashMap values = new HashMap();
+ for(int i = 0 ; i < n;i++) { + if (i == start) { + paths.put(start, start + ""); + }else{ + paths.put(i, start + "" + i + ""); + } + } + values.put(start,0); + while (!values.containsKey(end)) { + int k = -1; + int min = UNREACH; + for (int i = 0; i < n; i++) { + if (!isVisited[i] && graph[start][i].weight < min) { + min = graph[start][i].weight; + k = i; + } + } + values.put(k, min); + isVisited[k] = true; + + for (int i = 0; i < n; i++) { + if (!isVisited[i] && graph[start][k].weight + graph[k][i].weight < graph[start][i].weight) { + graph[start][i].weight = graph[start][k].weight + graph[k][i].weight; + String path = paths.get(k); + path += i + ""; + paths.put(i,path); + } + } + } + System.out.println("从起始点 " + start + " 到终点 " + end + " 的最短路"); + String path = paths.get(end); + for(int i = 0; i < path.length();i++) { + System.out.print(path.charAt(i)); + if (i != path.length() - 1){ + System.out.print("-->");
+ }
+ }
+ System.out.println("最短路径的值为 " + values.get(end));
+ }
+
+
+ public static class Weight {
+ int weight;
+
+ public Weight() {
+ this(UNREACH);
+ }
+
+ public Weight(int weight) {
+ this.weight = weight;
+ }
+ }
+}
diff --git a/src/main/java/cn/byhieg/algorithmtutorial/RedBlackTree.java b/src/main/java/cn/byhieg/algorithmtutorial/RedBlackTree.java
new file mode 100644
index 0000000..c895f7b
--- /dev/null
+++ b/src/main/java/cn/byhieg/algorithmtutorial/RedBlackTree.java
@@ -0,0 +1,326 @@
+package cn.byhieg.algorithmtutorial;
+
+/**
+ * Created by byhieg on 2017年6月24日.
+ * Mail to byhieg@gmail.com
+ */
+
+
+/**
+ * 红黑树,一种通过红黑两种节点来维持二叉搜索树的一种树
+ * 这样树比原先的BST而言,不会出现最坏的查找情况是o(N)的情况
+ * 但是对于插入和删除的节点而言,就需要调整树的平衡,也就是维持红黑树的定义
+ *
+ * 红黑树的定义如下:
+ * 1. 任何节点要不是黑色要不是红色
+ * 2. 根节点是黑色节点
+ * 3. 红节点的两个子节点都是黑色节点
+ * 4. 空节点是黑色节点
+ * 5. 任何一个节点下面遍历其子孙的叶子节点,经过的黑色节点的个数必须相等。
+ *
+ * 红黑树也是通过第5点进行维持平衡的,而为了维持平衡,需要对树进行调整,即进行左旋,右旋。
+
+ */
+public class RedBlackTree {
+
+ Node root;
+
+ public RedBlackTree() {
+ }
+
+ public RedBlackTree(int value) {
+ root = new Node(value);
+ }
+
+ public Node find(int value) {
+ if (root == null) {
+ throw new RuntimeException("树是空的");
+ }
+
+ Node currentNode = root;
+ while (currentNode != null && currentNode.getValue() != value) {
+ if (currentNode.getValue() < value) { + currentNode = currentNode.getLeft(); + } else { + currentNode = currentNode.getRight(); + } + } + + return currentNode; + } + + + public void insertNode(int value) { + Node node = new Node(value); + insertNode(node); + + } + + /** + * 插入节点 + * 该方法首先找到要插入的位置,然后设置插入的节点为红色节点 + * 然后因为可能会破坏平衡,因此需要进行平衡调整 + * + * @param node + */ + public void insertNode(Node node) { + int cmp; + Node y = null; + Node x = this.root; + + while (x != null) { + y = x; + cmp = node.getValue() - x.getValue(); + if (cmp < 0) { + x = x.left; + } else { + x = x.right; + } + } + + node.parent = y; + if (y != null) { + cmp = node.getValue() - y.getValue(); + if (cmp < 0) { + y.left = node; + } else { + y.right = node; + } + } else { + this.root = node; + } + + node.isRed = true; + insertFixUp(node); + + } + + /** + * 插入修复: 新插入的节点是红色节点,插入修复操作如果遇到父节点的颜色为黑色则修复结束 + * 也就是说只有在父节点为红色节点的时候才需要插入修复操作 + * 插入修复操作分为3种情况, + * 1. 叔叔节点也为红色节点 + * 2. 叔叔节点为空,且祖父节点,父节点与新节点在一个斜线上 + * 3. 叔叔节点为空,且祖父节点,父节点与新节点不在一个斜线上 + *
+ *
+ * 解决办法:对于第一种,只需要将祖父节点与父节点以及叔叔节点的颜色对调即可。
+ * 即原祖父节点是黑色,现在变成红色,父节点与叔叔节点都变成黑色。
+ * 对于第二种,我们将新插入的节点为C,父节点为B,祖父节点为A.
+ * 如果BC都是左节点,要现将A右旋,然后调整B与A的颜色,即B变成黑色,A变成红色
+ * 如果BC都是右节点,要现将A左旋,然后调整B与A的颜色,即B变成黑色,A变成红色
+ * 对于第三种,我们将新插入的节点为C,父节点为B,祖父节点为A.
+ * 如果C为右节点,B为左节点,要先将B左旋,然后就变成第二种的情况
+ * 如果C为左节点,B为右节点,要先B右旋,然后就变成第二种的情况
+ *
+ * @param node
+ */
+ private void insertFixUp(Node node) {
+ Node parent, grandParent, uncle;
+ while ((parent = parentOf(node)) != null && parent.isRed()) {
+ grandParent = parentOf(node);
+ //如果父节点是祖父节点的左孩子
+ if (parent == grandParent.left) {
+ uncle = grandParent.right;
+ //第一种情况
+ if ((uncle != null) && uncle.isRed()) {
+ uncle.makeBlack();
+ parent.makeBlack();
+ grandParent.makeRed();
+ node = grandParent;
+ continue;
+ }
+ //将第三种情况变成第二种情况
+ if (parent.right == node) {
+ Node tmp;
+ rotateLeft(parent);
+ tmp = parent;
+ parent = node;
+ node = tmp;
+ }
+ parent.makeBlack();
+ grandParent.makeRed();
+ rotateRight(grandParent);
+ } else {
+ uncle = grandParent.left;
+ if ((uncle != null) && uncle.isRed()) {
+ uncle.makeBlack();
+ parent.makeBlack();
+ grandParent.makeRed();
+ node = grandParent;
+ continue;
+ }
+
+ if (parent.left == node) {
+ Node tmp;
+ rotateRight(parent);
+ tmp = parent;
+ parent = node;
+ node = tmp;
+ }
+
+ parent.makeBlack();
+ grandParent.makeRed();
+ rotateLeft(grandParent);
+
+ }
+
+ }
+
+ root.makeBlack();
+ }
+
+
+ /**
+ * 对红黑树的节点(y)进行右旋转
+ *
+ * 右旋示意图(对节点y进行左旋):
+ * py py
+ * / /
+ * y x
+ * / \ --(右旋)-. / \ #
+ * x ry lx y
+ * / \ / \ #
+ * lx rx rx ry
+ *
+ * @param y 待旋转的节点
+ */
+ private void rotateRight(Node y) {
+
+ Node x = y.left;
+
+ // 将 "x的右孩子" 设为 "y的左孩子";
+ // 如果"x的右孩子"不为空的话,将 "y" 设为 "x的右孩子的父亲"
+ y.left = x.right;
+ if (x.right != null)
+ x.right.parent = y;
+
+ // 将 "y的父亲" 设为 "x的父亲"
+ x.parent = y.parent;
+
+ if (y.parent == null) {
+ this.root = x; // 如果 "y的父亲" 是空节点,则将x设为根节点
+ } else {
+ if (y == y.parent.right)
+ y.parent.right = x; // 如果 y是它父节点的右孩子,则将x设为"y的父节点的右孩子"
+ else
+ y.parent.left = x; // (y是它父节点的左孩子) 将x设为"x的父节点的左孩子"
+ }
+
+ // 将 "y" 设为 "x的右孩子"
+ x.right = y;
+
+ // 将 "y的父节点" 设为 "x"
+ y.parent = x;
+ }
+
+ /**
+ *
+ * 对红黑树的节点(x)进行左旋转
+ *
+ * 左旋示意图(对节点x进行左旋):
+ * px px
+ * / /
+ * x y
+ * / \ --(左旋)-. / \ #
+ * lx y x ry
+ * / \ / \
+ * ly ry lx ly
+ *
+ * @param x 待旋转的节点
+ */
+ private void rotateLeft(Node x) {
+ Node y = x.getRight();
+ x.right = y.left;
+ if (y.left != null) {
+ y.left.parent = x;
+ }
+ y.parent = x.parent;
+ if (x.parent == null) {
+ root = y;
+ }else{
+ if (x.parent.left == x) {
+ x.parent.left = y;
+ }else{
+ x.parent.right = y;
+ }
+ }
+ y.left = x;
+ x.parent = y;
+ }
+
+ private Node parentOf(Node node) {
+ return node != null ? node.parent : null;
+ }
+
+
+ static class Node {
+ private int value;
+ private Node parent;
+ private boolean isRed;
+ private Node left;
+ private Node right;
+
+ public Node() {
+
+ }
+
+ public Node(int value) {
+ this.value = value;
+
+ }
+
+ public Node(int value, boolean isRed) {
+ this.value = value;
+ this.isRed = isRed;
+ }
+
+ public int getValue() {
+ return value;
+ }
+
+ public void setValue(int value) {
+ this.value = value;
+ }
+
+ public Node getParent() {
+ return parent;
+ }
+
+ public void setParent(Node parent) {
+ this.parent = parent;
+ }
+
+ public boolean isRed() {
+ return isRed;
+ }
+
+ public boolean isBlack() {
+ return !isRed();
+ }
+
+ public Node getLeft() {
+ return left;
+ }
+
+ public void setLeft(Node left) {
+ this.left = left;
+ }
+
+ public Node getRight() {
+ return right;
+ }
+
+ public void setRight(Node right) {
+ this.right = right;
+ }
+
+ public void makeRed() {
+ isRed = true;
+ }
+
+ public void makeBlack() {
+ isRed = false;
+ }
+ }
+}
diff --git a/src/main/java/cn/byhieg/algorithmtutorial/SingleLinkList.java b/src/main/java/cn/byhieg/algorithmtutorial/SingleLinkList.java
new file mode 100644
index 0000000..1de9643
--- /dev/null
+++ b/src/main/java/cn/byhieg/algorithmtutorial/SingleLinkList.java
@@ -0,0 +1,109 @@
+package cn.byhieg.algorithmtutorial;
+
+/**
+ * Created by byhieg on 17/5/2.
+ * Mail to byhieg@gmail.com
+ */
+public class SingleLinkList {
+
+
+ public Node head;
+
+ /**
+ * 在当前链表尾部插入一个节点
+ *
+ * @param data
+ * @return
+ */
+ public Node insertFromTail(int data) {
+ Node cur = getHead();
+ Node node = new Node(data);
+ if (cur == null) {
+ head = node;
+ return head;
+ } else {
+ while (cur.next != null) {
+ cur = cur.next;
+ }
+ cur.next = node;
+ }
+ return cur;
+ }
+
+ /**
+ * 在当前链表头部插入一个节点
+ *
+ * @param data
+ * @return
+ */
+ public Node insertFromHead(int data) {
+ Node node = new Node(data);
+ node.next = head;
+ head = node;
+ return head;
+ }
+
+ /**
+ * 反转链表的非递归实现
+ * @return
+ */
+ public Node reverseLinkList() {
+ if (head == null) {
+ return head;
+ }
+ Node reverseHead = null;
+ Node cur = head;
+ Node prev = null;
+ while (cur != null) {
+ Node next = cur.next;
+ if (next == null) {
+ reverseHead = cur;
+ }
+ cur.next = prev;
+ prev = cur;
+ cur = next;
+ }
+ return reverseHead;
+ }
+
+
+ /**
+ * 反转链表的递归实现
+ * @return
+ */
+ public Node reverseLinkList(Node head){
+ if (head == null || head.next == null) {
+ return head;
+ }
+ Node newNode = reverseLinkList(head.next);
+ head.next.next = head;
+ head.next = null;
+ return newNode;
+ }
+
+
+
+ /**
+ * 打印链表
+ */
+ public void printLinkList(Node head) {
+ Node cur = head;
+ while (cur != null) {
+ System.out.print(cur.data + " ");
+ cur = cur.next;
+ }
+ }
+
+ public Node getHead() {
+ return head;
+ }
+
+ public static class Node {
+ public int data;
+ public Node next;
+
+ public Node(int data) {
+ this.data = data;
+ }
+ }
+}
diff --git a/src/main/java/cn/byhieg/algorithmtutorial/Sort.java b/src/main/java/cn/byhieg/algorithmtutorial/Sort.java
new file mode 100644
index 0000000..6794e42
--- /dev/null
+++ b/src/main/java/cn/byhieg/algorithmtutorial/Sort.java
@@ -0,0 +1,320 @@
+package cn.byhieg.algorithmtutorial;
+
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.List;
+
+/**
+ * Created by shiqifeng on 2017年3月28日.
+ * Mail byhieg@gmail.com
+ */
+public class Sort {
+
+ /**
+ * 选择排序,每一轮排序,选择数组中数字最小的那一个放到指定的位置上。
+ * 时间复杂度o(n^2),无论数组顺序如何都要选择一个最小的值,因为数组的是否有序,不影响时间复杂度
+ * 空间复杂度o(1)
+ * 不稳定排序
+ * @param nums
+ */
+ public void chooseSort(int[] nums) {
+ int length = nums.length;
+ for (int i = 0; i < length; i++) { + int min = i;//申请额外的空间o(1) + for (int j = i + 1; j < length; j++) { + if (nums[min]> nums[j]) {
+ min = j;
+ }
+ }
+ //将最小的下标代表的数与i位置的进行交换
+ int tmp = nums[i];
+ nums[i] = nums[min];
+ nums[min] = tmp;
+ }
+ }
+
+ /**
+ * 直接插入排序,每一轮排序,都是在i坐标之前,包括i坐标的序列是有序的,但是并不是最终的排序位置。
+ * 时间复杂度o(n^2),对于第二重循环,只会在非有序的环境下才会执行每个元素后移,因此针对有序的数组,时间复杂度最好的情况是o(N)。
+ * 空间复杂度o(1)
+ * 稳定排序
+ * @param nums
+ */
+ public void insertDirectlySort(int[] nums) {
+ int length = nums.length;
+ for (int i = 1; i < length; i++) { + for (int j = i; j> 0; j--) {
+ //这一步导致该算法是稳定排序
+ if (nums[j] < nums[j - 1]) { + int tmp = nums[j - 1]; + nums[j - 1] = nums[j]; + nums[j] = tmp; + } + } + } + } + + /** + * 折半插入排序,针对直接排序而言,每一个要插入的元素都是插入在有序的数组中,因此,只需要查找到插入的位置即可,查找的方式利用二分查找 + * 时间复杂度和直接插入是一样的,只是快在了查找的过程中,还是o(N^2),最好的环境下是o(N) + * 空间复杂度还是o(1) + * + * @param nums + */ + public void insertBinarySort(int[] nums) { + int length = nums.length; + for (int i = 1; i < length; i++) { + int tmp = nums[i]; + int low = 0; + int high = i - 1; + while (low <= high) { + int mid = (low + high) / 2; + if (tmp < nums[mid]) { + high = mid - 1; + } else { + low = mid + 1; + } + } + + for (int j = i; j>= low + 1; j--) {
+ nums[j] = nums[j - 1];
+ }
+ nums[low] = tmp;
+ }
+ }
+
+ /**
+ * 冒泡排序,每i轮排序,就是不断交换两个元素,直到将最大的元素放到n - i的位置上
+ * 这种实现是按照算法定义的,但是效率是最低的
+ * 时间复杂度o(n^2)
+ * 空间复杂度o(1)
+ * 稳定排序
+ * @param nums
+ */
+ public void bubbleSort1(int[] nums) {
+ int length = nums.length;
+ for (int i = 1; i < length; i++) { + for (int j = 0; j < length - i; j++) { + //这一步导致该算法是稳定排序 + if (nums[j]> nums[j + 1]) {
+ int tmp = nums[j];
+ nums[j] = nums[j + 1];
+ nums[j + 1] = tmp;
+ }
+ }
+ }
+ }
+
+ /**
+ * 冒泡排序,高效率实现,因为只需要用一个flag变量来记录本次的排序,是否修改
+ * 如果没有修改,说明已经有序
+ *
+ * @param nums
+ */
+ public void bubbleSort2(int[] nums) {
+ int length = nums.length;
+ boolean flag = true;
+ while (flag) {
+ flag = false;
+ for (int j = 0; j < length - 1; j++) { + if (nums[j]> nums[j + 1]) {
+ int tmp = nums[j];
+ nums[j] = nums[j + 1];
+ nums[j + 1] = tmp;
+ flag = true;
+ }
+ }
+ length--;
+ }
+ }
+
+ /**
+ * 归并排序,将数组一分为二,对于每一子数组继续进行上述步骤,直到子数组只有1个元素,那么自然是有序的。
+ * 然后不断合并两个数组,直到合并到整个数组。
+ * 时间复杂度o(NlgN)
+ * 空间复杂度o(N)
+ * @param nums
+ */
+ public void mergeSort(int[] nums) {
+ int length = nums.length;
+ int low = 0;
+ int high = length - 1;
+ realSort(nums, low, high);
+ }
+
+ /**
+ * 归并排序真正的sort函数
+ * @param nums 待排序的数组
+ * @param low 最低位
+ * @param high 最高位
+ */
+ private void realSort(int[] nums, int low, int high) {
+ int mid = (low + high) / 2;
+ if (low < high) { + realSort(nums, low, mid); + realSort(nums, mid + 1, high); + realMerge(nums, low, mid, high); + } + } + + private void realMerge(int[] nums, int low, int mid, int high) { + int[] tmpNums = new int[high - low + 1]; + int leftPoint = low; + int rightPoint = mid + 1; + int index = 0; + + while (leftPoint <= mid && rightPoint <= high) { + if (nums[leftPoint] < nums[rightPoint]) { + tmpNums[index++] = nums[leftPoint++]; + }else{ + tmpNums[index++] = nums[rightPoint++]; + } + } + + while (leftPoint <= mid) { + tmpNums[index++] = nums[leftPoint++]; + } + while (rightPoint <= high) { + tmpNums[index++] = nums[rightPoint++]; + } + + System.arraycopy(tmpNums, 0, nums, low, tmpNums.length); + } + + /** + * 快速排序,选定一个切分元素,每一轮排序后,都保证切分元素之前的元素都小于切分元素,切分元素之后的元素都大于切分元素 + * 时间复杂度o(NlgN) + * 空间复杂度o(lgN) + * 不稳定排序 + * @param nums + */ + public void quickSort(int[] nums) { + int low = 0; + int high = nums.length - 1; + sort(nums, low, high); + } + + /** + * 快速排序的递归实现 + * + * @param nums + * @param low + * @param high + */ + public void sort(int[] nums, int low, int high) { + if (low>= high) return;
+ int j = partition(nums, low, high);
+ sort(nums, low, j - 1);
+ sort(nums, j + 1, high);
+ }
+
+ /**
+ * 快速排序的辅助方法,来对排序的数组,进行切分,
+ *
+ * @param nums
+ * @param low
+ * @param high
+ * @return
+ */
+ public int partition(int[] nums, int low, int high) {
+ int i = low;
+ int j = high;
+ int x = nums[i];
+ while (i < j) { + //从右向左找到nums[j]小于x的元素 + while (i < j && nums[j]>= x) j--;
+ if (i < j) { + nums[i] = nums[j]; + i++; + } + + //从左向右找到nums[i]大于x的元素 + while (i < j && nums[i] <= x) i++; + if (i < j) { + nums[j] = nums[i]; + j--; + } + } + nums[i] = x; + return i; + } + + + /** + * 堆排序,建立一个小顶堆,小顶堆满足父节点比两个子节点的值要小 + * 堆的性质满足:1. 只能在堆顶删除元素 + * 2. 只能在堆的最后一位存元素。 + * 3. 堆的存储利用数组,满足i节点是父节点,则子节点是2 * i+ 1,2 * i + 2 + * 4. 堆的两种建方法,第一种是从上到下,@see sink(),第二种是从下到上 @see swim + * 5. 堆排序是指在弄好的堆中,输出第一个元素,然后将最后一个元素与第一个元素互换,换后调用sink,找到自己的位置后,在重复这个步骤,就输出一个有序的堆 + * 6. 如果要生序就需要大顶堆,要降序就需要小顶堆。 + * 时间复杂度:o(NlgN) + * 空间复杂度: o(1) + * 这是小顶堆的排序,所以nums数组最后是降序的 + * 不稳定,不稳定的原因在建堆的时候,就可能把相同元素的位置换了,比如两个相同元素在不同的子树上 + * @param nums + */ + public void heapSort(int[] nums) { + int length = nums.length; +// for (int i = 0; i < length; i++) { +// swim(nums, i); +// } + //只能从前一半开始sink + for (int i = length / 2 ; i>= 0;i--) {
+ sink(nums,i,length);
+ }
+ while (length> 0) {
+ int temp = nums[0];
+ nums[0] = nums[length - 1];
+ nums[length - 1] = temp;
+ length--;
+ sink(nums, 0, length);
+ }
+ }
+
+ /**
+ * 将i放入对堆中,i的父节点是(i - 1)/ 2,父节点的值是小于他的两个子节点的
+ * i节点放入后,要向上移动,如果父节点比i节点的值大,则i节点要继续上移。
+ *
+ * @param nums
+ * @param i
+ */
+ private void swim(int nums[], int i) {
+ while (i> 0) {
+ int father = (i - 1) / 2;
+ if (nums[father]> nums[i]) {
+ int temp = nums[father];
+ nums[father] = nums[i];
+ nums[i] = temp;
+ }
+ i = father;
+ }
+ }
+
+
+ /**
+ * 从i节点由上到下开始调整,i节点的子节点为2*i + 1, 2 * i + 2
+ * i节点要向下移动,直到满足i节点小于两个子节点
+ *
+ * @param nums nums[] 数组
+ * @param i i节点
+ */
+ public void sink(int [] nums, int i,int n) {
+ int son = 2 * i + 1;
+ while (son <= n - 1) { + if (son < n - 1 && nums[son]> nums[son + 1]) son++;
+ if (nums[i]> nums[son]) {
+ int temp = nums[i];
+ nums[i] = nums[son];
+ nums[son] = temp;
+ i = son;
+ son = 2 * i + 1;
+ }else{
+ break;
+ }
+ }
+ }
+
+
+
+}
diff --git a/src/main/java/cn/byhieg/bitoperatetutorial/BitOperate.java b/src/main/java/cn/byhieg/bitoperatetutorial/BitOperate.java
new file mode 100644
index 0000000..680408b
--- /dev/null
+++ b/src/main/java/cn/byhieg/bitoperatetutorial/BitOperate.java
@@ -0,0 +1,14 @@
+package cn.byhieg.bitoperatetutorial;
+
+/**
+ * Created by byhieg on 2017年6月27日.
+ * Mail to byhieg@gmail.com
+ */
+public class BitOperate {
+
+
+ public String getRightestOne(int n){
+ int res = n & (~n + 1);
+ return Integer.toBinaryString(res);
+ }
+}
diff --git a/src/main/java/cn/byhieg/collectiontutorial/maptutorial/HashMapExample.java b/src/main/java/cn/byhieg/collectiontutorial/maptutorial/HashMapExample.java
index e3a51ac..9e55ef1 100644
--- a/src/main/java/cn/byhieg/collectiontutorial/maptutorial/HashMapExample.java
+++ b/src/main/java/cn/byhieg/collectiontutorial/maptutorial/HashMapExample.java
@@ -1,8 +1,6 @@
package cn.byhieg.collectiontutorial.maptutorial;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.Map;
+import java.util.*;
/**
* Created by shiqifeng on 2017年2月24日.
diff --git a/src/main/java/cn/byhieg/designpatterntutorial/builder/Person.java b/src/main/java/cn/byhieg/designpatterntutorial/builder/Person.java
new file mode 100644
index 0000000..91077fd
--- /dev/null
+++ b/src/main/java/cn/byhieg/designpatterntutorial/builder/Person.java
@@ -0,0 +1,73 @@
+package cn.byhieg.designpatterntutorial.builder;
+
+/**
+ * Created by shiqifeng on 2017年5月7日.
+ * Mail byhieg@gmail.com
+ */
+public class Person {
+
+ private int age;
+ private String name;
+ private int height;
+ private int weight;
+
+ public int getAge() {
+ return age;
+ }
+
+ public String getName() {
+ return name;
+ }
+
+ public int getHeight() {
+ return height;
+ }
+
+ public int getWeight() {
+ return weight;
+ }
+
+ public Person(Builder builder) {
+ age = builder.age;
+ name = builder.name;
+ height = builder.height;
+ weight = builder.weight;
+ }
+
+ @Override
+ public String toString() {
+ return "age = " + age + " name = " + name + " height = " + height + " weight = " + weight;
+ }
+
+ public static class Builder{
+
+ private int age;
+ private String name;
+ private int height;
+ private int weight;
+
+ public Builder setAge(int age) {
+ this.age = age;
+ return this;
+ }
+
+ public Builder setName(String name) {
+ this.name = name;
+ return this;
+ }
+
+ public Builder setHeight(int height) {
+ this.height = height;
+ return this;
+ }
+
+ public Builder setWeight(int weight) {
+ this.weight = weight;
+ return this;
+ }
+
+ public Person build() {
+ return new Person(this);
+ }
+ }
+}
diff --git a/src/main/java/cn/byhieg/designpatterntutorial/builder/SimpleDialog.java b/src/main/java/cn/byhieg/designpatterntutorial/builder/SimpleDialog.java
new file mode 100644
index 0000000..0d90062
--- /dev/null
+++ b/src/main/java/cn/byhieg/designpatterntutorial/builder/SimpleDialog.java
@@ -0,0 +1,78 @@
+package cn.byhieg.designpatterntutorial.builder;
+
+/**
+ * Created by shiqifeng on 2017年5月7日.
+ * Mail byhieg@gmail.com
+ */
+public class SimpleDialog {
+
+
+ public SimpleDialogController controller;
+
+ public SimpleDialog(){
+ controller = new SimpleDialogController();
+ }
+
+ public void setIcon(String icon) {
+ controller.setIcon(icon);
+ }
+
+ public void setTitle(String title) {
+ controller.setTitle(title);
+ }
+
+ public void setMessage(String message) {
+ controller.setMessage(message);
+ }
+
+ public void setPositiveButton(String positiveButton) {
+ controller.setPositiveButton(positiveButton);
+ }
+
+ public void setNegativeButton(String negativeButton) {
+ controller.setNegativeButton(negativeButton);
+ }
+
+
+ public static class Builder{
+ SimpleDialogController.DialogParams P;
+
+ public Builder(){
+ P = new SimpleDialogController.DialogParams();
+ }
+
+ public Builder setIcon(String icon){
+ P.icon = icon;
+ return this;
+ }
+
+ public Builder setTitle(String title) {
+ P.title = title;
+ return this;
+ }
+
+ public Builder setMessage(String message) {
+ P.message = message;
+ return this;
+ }
+
+ public Builder setPositiveButton(String positiveButton) {
+ P.positiveButton = positiveButton;
+ return this;
+ }
+
+ public Builder setNegativeButton(String negativeButton) {
+ P.negativeButton = negativeButton;
+ return this;
+ }
+
+ public SimpleDialog create(){
+ SimpleDialog dialog = new SimpleDialog();
+ P.apply(dialog.controller);
+ System.out.println(" ICON = " + P.icon + " MESSAGE = " + P.message + " positiveButton = " + P.positiveButton + " negativeButton" + P.negativeButton);
+ return dialog;
+ }
+ }
+
+
+}
diff --git a/src/main/java/cn/byhieg/designpatterntutorial/builder/SimpleDialogController.java b/src/main/java/cn/byhieg/designpatterntutorial/builder/SimpleDialogController.java
new file mode 100644
index 0000000..4d41b74
--- /dev/null
+++ b/src/main/java/cn/byhieg/designpatterntutorial/builder/SimpleDialogController.java
@@ -0,0 +1,81 @@
+package cn.byhieg.designpatterntutorial.builder;
+
+/**
+ * Created by shiqifeng on 2017年5月7日.
+ * Mail byhieg@gmail.com
+ */
+public class SimpleDialogController {
+
+ private String icon;
+ private String title;
+ private String message;
+ private String positiveButton;
+ private String negativeButton;
+
+ public void setIcon(String icon) {
+ this.icon = icon;
+ }
+
+ public void setTitle(String title) {
+ this.title = title;
+ }
+
+ public void setMessage(String message) {
+ this.message = message;
+ }
+
+ public void setPositiveButton(String positiveButton) {
+ this.positiveButton = positiveButton;
+ }
+
+ public void setNegativeButton(String negativeButton) {
+ this.negativeButton = negativeButton;
+ }
+
+ public String getIcon() {
+ return icon;
+ }
+
+ public String getTitle() {
+ return title;
+ }
+
+ public String getMessage() {
+ return message;
+ }
+
+ public String getPositiveButton() {
+ return positiveButton;
+ }
+
+ public String getNegativeButton() {
+ return negativeButton;
+ }
+
+ public static class DialogParams{
+ public String icon;
+ public String title;
+ public String message;
+ public String positiveButton;
+ public String negativeButton;
+
+ public void apply(SimpleDialogController controller) {
+ if (icon != null) {
+ controller.setIcon(icon);
+ }
+ if (title != null) {
+ controller.setTitle(title);
+ }
+ if (message != null) {
+ controller.setMessage(message);
+ }
+ if (positiveButton != null) {
+ controller.setPositiveButton(positiveButton);
+ }
+ if (negativeButton != null) {
+ controller.setNegativeButton(negativeButton);
+ }
+ }
+ }
+
+}
diff --git a/src/main/java/cn/byhieg/designpatterntutorial/proxy/dynamicproxy/Client.java b/src/main/java/cn/byhieg/designpatterntutorial/proxy/dynamicproxy/Client.java
new file mode 100644
index 0000000..6d6a78d
--- /dev/null
+++ b/src/main/java/cn/byhieg/designpatterntutorial/proxy/dynamicproxy/Client.java
@@ -0,0 +1,19 @@
+package cn.byhieg.designpatterntutorial.proxy.dynamicproxy;
+
+
+import java.lang.reflect.Proxy;
+
+/**
+ * Created by shiqifeng on 2017年3月17日.
+ * Mail byhieg@gmail.com
+ */
+public class Client {
+
+ public static void main(String[] args) {
+ Subject realSubject = new RealSubject();
+ DynamicProxy proxy = new DynamicProxy(realSubject);
+ ClassLoader classLoader = realSubject.getClass().getClassLoader();
+ Subject subject = (Subject) Proxy.newProxyInstance(classLoader, new Class[]{Subject.class}, proxy);
+ subject.visit();
+ }
+}
diff --git a/src/main/java/cn/byhieg/designpatterntutorial/proxy/dynamicproxy/DynamicProxy.java b/src/main/java/cn/byhieg/designpatterntutorial/proxy/dynamicproxy/DynamicProxy.java
index abe4fe1..5589d9c 100644
--- a/src/main/java/cn/byhieg/designpatterntutorial/proxy/dynamicproxy/DynamicProxy.java
+++ b/src/main/java/cn/byhieg/designpatterntutorial/proxy/dynamicproxy/DynamicProxy.java
@@ -10,6 +10,11 @@
public class DynamicProxy implements InvocationHandler {
private Object object;
+
+ public DynamicProxy(Object object) {
+ this.object = object;
+ }
+
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = method.invoke(object, args);
diff --git a/src/main/java/cn/byhieg/designpatterntutorial/proxy/dynamicproxy/RealSubject.java b/src/main/java/cn/byhieg/designpatterntutorial/proxy/dynamicproxy/RealSubject.java
new file mode 100644
index 0000000..ab391f7
--- /dev/null
+++ b/src/main/java/cn/byhieg/designpatterntutorial/proxy/dynamicproxy/RealSubject.java
@@ -0,0 +1,15 @@
+package cn.byhieg.designpatterntutorial.proxy.dynamicproxy;
+
+
+/**
+ * Created by shiqifeng on 2017年3月17日.
+ * Mail byhieg@gmail.com
+ */
+public class RealSubject implements Subject {
+
+ private String name = "byhieg";
+ @Override
+ public void visit() {
+ System.out.println(name);
+ }
+}
diff --git a/src/main/java/cn/byhieg/designpatterntutorial/proxy/dynamicproxy/Subject.java b/src/main/java/cn/byhieg/designpatterntutorial/proxy/dynamicproxy/Subject.java
new file mode 100644
index 0000000..f662e32
--- /dev/null
+++ b/src/main/java/cn/byhieg/designpatterntutorial/proxy/dynamicproxy/Subject.java
@@ -0,0 +1,10 @@
+package cn.byhieg.designpatterntutorial.proxy.dynamicproxy;
+
+/**
+ * Created by shiqifeng on 2017年3月17日.
+ * Mail byhieg@gmail.com
+ */
+public interface Subject {
+
+ void visit();
+}
diff --git a/src/main/java/cn/byhieg/threadtutorial/concurrent/atom/AtomFactory.java b/src/main/java/cn/byhieg/threadtutorial/concurrent/atom/AtomFactory.java
new file mode 100644
index 0000000..f5da772
--- /dev/null
+++ b/src/main/java/cn/byhieg/threadtutorial/concurrent/atom/AtomFactory.java
@@ -0,0 +1,36 @@
+package cn.byhieg.threadtutorial.concurrent.atom;
+
+import java.util.concurrent.atomic.*;
+
+/**
+ * Created by shiqifeng on 2017年5月5日.
+ * Mail byhieg@gmail.com
+ */
+public class AtomFactory {
+
+ private static final AtomFactory atomFactory = new AtomFactory();
+
+ private AtomFactory(){
+
+ }
+
+ public static AtomFactory getInstance(){
+ return atomFactory;
+ }
+
+ public AtomicInteger createAtomInt(int a){
+ return new AtomicInteger(a);
+ }
+
+ public AtomicIntegerArray createAtomArray(int[] a) {
+ return new AtomicIntegerArray(a);
+ }
+
+ public AtomicReference createAtomReference(MyObject object){
+ return new AtomicReference();
+ }
+
+ public AtomicIntegerFieldUpdater createAtomIntegerUpdate(String fieldName) {
+ return AtomicIntegerFieldUpdater.newUpdater(MyObject.class, fieldName);
+ }
+}
diff --git a/src/main/java/cn/byhieg/threadtutorial/concurrent/atom/MyObject.java b/src/main/java/cn/byhieg/threadtutorial/concurrent/atom/MyObject.java
new file mode 100644
index 0000000..69ebbb6
--- /dev/null
+++ b/src/main/java/cn/byhieg/threadtutorial/concurrent/atom/MyObject.java
@@ -0,0 +1,12 @@
+package cn.byhieg.threadtutorial.concurrent.atom;
+
+/**
+ * Created by shiqifeng on 2017年5月5日.
+ * Mail byhieg@gmail.com
+ */
+public class MyObject {
+
+ public String name = "byhieg";
+ public int age = 24;
+ public volatile int id = 1;
+}
diff --git a/src/main/java/cn/byhieg/threadtutorial/concurrent/blocking/ArrayBlock.java b/src/main/java/cn/byhieg/threadtutorial/concurrent/blocking/ArrayBlock.java
new file mode 100644
index 0000000..3687b31
--- /dev/null
+++ b/src/main/java/cn/byhieg/threadtutorial/concurrent/blocking/ArrayBlock.java
@@ -0,0 +1,34 @@
+package cn.byhieg.threadtutorial.concurrent.blocking;
+
+import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
+
+import javax.sound.midi.SoundbankResource;
+import java.lang.management.LockInfo;
+import java.util.concurrent.*;
+
+/**
+ * Created by byhieg on 17/5/3.
+ * Mail to byhieg@gmail.com
+ */
+public class ArrayBlock {
+
+ private BlockingQueue blockingQueue;
+
+ public ArrayBlock(int index) {
+ switch (index) {
+ case 0:
+ blockingQueue = new ArrayBlockingQueue(3);
+ break;
+ case 1:
+ blockingQueue = new LinkedBlockingQueue();
+ break;
+ case 2:
+ blockingQueue = new SynchronousQueue();
+ break;
+ }
+ }
+
+ public BlockingQueue getBlockingQueue() {
+ return blockingQueue;
+ }
+}
diff --git a/src/main/java/cn/byhieg/threadtutorial/concurrent/blocking/Costumer.java b/src/main/java/cn/byhieg/threadtutorial/concurrent/blocking/Costumer.java
new file mode 100644
index 0000000..f88b45f
--- /dev/null
+++ b/src/main/java/cn/byhieg/threadtutorial/concurrent/blocking/Costumer.java
@@ -0,0 +1,31 @@
+package cn.byhieg.threadtutorial.concurrent.blocking;
+
+import java.util.concurrent.BlockingQueue;
+
+/**
+ * Created by byhieg on 17/5/3.
+ * Mail to byhieg@gmail.com
+ */
+public class Costumer extends Thread{
+
+ private BlockingQueue blockingQueue;
+
+ public Costumer(ArrayBlock arrayBlock) {
+ blockingQueue = arrayBlock.getBlockingQueue();
+ this.setName("Costumer");
+ }
+
+ @Override
+ public void run() {
+ super.run();
+ while (true) {
+ try {
+ Thread.sleep(5000);
+ String str = blockingQueue.take();
+ System.out.println(getName() + " 取出数据 " + str);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+}
diff --git a/src/main/java/cn/byhieg/threadtutorial/concurrent/blocking/Producer.java b/src/main/java/cn/byhieg/threadtutorial/concurrent/blocking/Producer.java
new file mode 100644
index 0000000..a2d12eb
--- /dev/null
+++ b/src/main/java/cn/byhieg/threadtutorial/concurrent/blocking/Producer.java
@@ -0,0 +1,29 @@
+package cn.byhieg.threadtutorial.concurrent.blocking;
+
+import java.util.concurrent.BlockingQueue;
+
+/**
+ * Created by byhieg on 17/5/3.
+ * Mail to byhieg@gmail.com
+ */
+public class Producer extends Thread {
+
+ private BlockingQueue blockingQueue;
+ @Override
+ public void run() {
+ super.run();
+ for (int i = 0 ; i < 5;i++) { + try { + blockingQueue.put(i + ""); + System.out.println(getName() + " 生产数据"); + } catch (InterruptedException e) { + e.printStackTrace(); + } + } + } + + public Producer(ArrayBlock arrayBlock){ + this.setName("Producer"); + blockingQueue = arrayBlock.getBlockingQueue(); + } +} diff --git a/src/test/java/cn/byhieg/algorithmtutorialtest/BinaryTreeTest.java b/src/test/java/cn/byhieg/algorithmtutorialtest/BinaryTreeTest.java new file mode 100644 index 0000000..9c1cfa5 --- /dev/null +++ b/src/test/java/cn/byhieg/algorithmtutorialtest/BinaryTreeTest.java @@ -0,0 +1,88 @@ +package cn.byhieg.algorithmtutorialtest; + +import cn.byhieg.algorithmtutorial.BinaryTree; +import junit.framework.TestCase; + +/** + * Created by byhieg on 17/4/15. + * Mail to byhieg@gmail.com + */ +public class BinaryTreeTest extends TestCase { + + BinaryTree.Node root = new BinaryTree.Node(1); + public void setUp() throws Exception { + super.setUp(); + BinaryTree.Node[] nodes = new BinaryTree.Node[10]; + nodes[0] = new BinaryTree.Node(2); + root.left = nodes[0]; + for (int i = 1 ; i < 10;i++) { + nodes[i] = new BinaryTree.Node(2 + i); + if (i % 2 == 0){ + nodes[i - 1].left = nodes[i]; + }else{ + nodes[i - 1].right = nodes[i]; + } + } + + } + + public void tearDown() throws Exception { + System.out.println(); + } + + public void testPreOrder1() throws Exception { + System.out.println("递归的先续遍历"); + BinaryTree.preOrder1(root); + } + + public void testPreOrder2() throws Exception { + System.out.println("非递归的先续遍历"); + BinaryTree.preOrder2(root); + } + + + public void testInOrder1() throws Exception { + System.out.println("递归的中序遍历"); + BinaryTree.inOrder1(root); + } + + public void testInOrder2() throws Exception { + System.out.println("非递归的中序遍历"); + BinaryTree.inOrder2(root); + } + + public void testPostOrder1() throws Exception { + System.out.println("递归的后续遍历"); + BinaryTree.postOrder1(root); + } + + public void testPostOrder2() throws Exception { + System.out.println("非递归的后续遍历"); + BinaryTree.postOrder2(root); + } + + public void testLevelOrder() throws Exception { + System.out.println("层次遍历"); + BinaryTree.levelOrder(root); + } + + public void testGetNodes() throws Exception { + System.out.print("节点数" + BinaryTree.getNodes(root)); + } + + public void testGetLeafs() throws Exception { + System.out.print("叶子数" + BinaryTree.getLeafs(root)); + } + + public void testGetHeight() throws Exception { + System.out.print("树的高度" + BinaryTree.getHeight(root)); + } + + public void testCalcKNodes() throws Exception { + System.out.print("第2层的节点数" + BinaryTree.calcKNodes(root,2)); + } + + public void testMirror() throws Exception { + BinaryTree.mirror(root); + } +} \ No newline at end of file diff --git a/src/test/java/cn/byhieg/algorithmtutorialtest/FindTest.java b/src/test/java/cn/byhieg/algorithmtutorialtest/FindTest.java new file mode 100644 index 0000000..53914a9 --- /dev/null +++ b/src/test/java/cn/byhieg/algorithmtutorialtest/FindTest.java @@ -0,0 +1,34 @@ +package cn.byhieg.algorithmtutorialtest; + +import cn.byhieg.algorithmtutorial.Find; +import junit.framework.TestCase; + +/** + * Created by shiqifeng on 2017/3/29. + * Mail byhieg@gmail.com + */ +public class FindTest extends TestCase { + int[] nums; + int result; + public void setUp() throws Exception { + super.setUp(); + nums = new int[]{}; + } + + public void tearDown() throws Exception { + System.out.println(result); + } + + public void testBinarySerachFind() throws Exception { + result = new Find().binarySearchFind(nums,2); + } + +// public void testBinarySearchMinFind() throws Exception { +// result = new Find().binarySearchMinFind(nums,1); +// } + +// public void testBinarySearchMaxFind() throws Exception { +// result = new Find().binarySearchMaxFind(nums, 2); +// } + +} \ No newline at end of file diff --git a/src/test/java/cn/byhieg/algorithmtutorialtest/GraphMatrixTest.java b/src/test/java/cn/byhieg/algorithmtutorialtest/GraphMatrixTest.java new file mode 100644 index 0000000..1851a18 --- /dev/null +++ b/src/test/java/cn/byhieg/algorithmtutorialtest/GraphMatrixTest.java @@ -0,0 +1,56 @@ +package cn.byhieg.algorithmtutorialtest; + +import cn.byhieg.algorithmtutorial.GraphMatrix; +import junit.framework.TestCase; + +/** + * Created by shiqifeng on 2017/4/5. + * Mail byhieg@gmail.com + */ +public class GraphMatrixTest extends TestCase { + + GraphMatrix graphMatrix; + GraphMatrix.Weight[][] weights; + public void setUp() throws Exception { + super.setUp(); + weights = new GraphMatrix.Weight[5][5]; + for (int i = 0 ; i < weights.length;i++) + for (int j = 0 ; j < weights[i].length;j++){ + weights[i][j] = new GraphMatrix.Weight(); + weights[j][i] = new GraphMatrix.Weight(); + } + + weights[0][1] = new GraphMatrix.Weight(100); + weights[1][2] = new GraphMatrix.Weight(10); + weights[2][3] = new GraphMatrix.Weight(20); + weights[3][1] = new GraphMatrix.Weight(25); + weights[2][4] = new GraphMatrix.Weight(20); + + weights[1][0] = new GraphMatrix.Weight(100); + weights[2][1] = new GraphMatrix.Weight(10); + weights[3][2] = new GraphMatrix.Weight(20); + weights[1][3] = new GraphMatrix.Weight(25); + weights[4][2] = new GraphMatrix.Weight(20); + + + graphMatrix = new GraphMatrix(weights); + } + + public void tearDown() throws Exception { + + } + + public void testBFS() throws Exception { + graphMatrix.BFS(4); + + } + + public void testDFS() throws Exception { + graphMatrix.DFS(0); + } + + public void testDijkstra() throws Exception { + graphMatrix.dijkstra(1,2); + } + +} \ No newline at end of file diff --git a/src/test/java/cn/byhieg/algorithmtutorialtest/SingleLinkListTest.java b/src/test/java/cn/byhieg/algorithmtutorialtest/SingleLinkListTest.java new file mode 100644 index 0000000..e7f2145 --- /dev/null +++ b/src/test/java/cn/byhieg/algorithmtutorialtest/SingleLinkListTest.java @@ -0,0 +1,69 @@ +package cn.byhieg.algorithmtutorialtest; + +import cn.byhieg.algorithmtutorial.SingleLinkList; +import junit.framework.TestCase; + +/** + * Created by byhieg on 17/5/2. + * Mail to byhieg@gmail.com + */ +public class SingleLinkListTest extends TestCase { + + + SingleLinkList linkList; + + public void setUp() throws Exception { + super.setUp(); + linkList = new SingleLinkList(); + } + + public void tearDown() throws Exception { +// linkList.printLinkList(linkList.head); +// System.out.println(); + } + + + public void testInsertFromTail() throws Exception { +// linkList.insertFromTail(1); +// linkList.insertFromTail(2); +// linkList.insertFromTail(3); +// linkList.insertFromTail(4); +// linkList.insertFromTail(5); +// linkList.insertFromTail(6); +// System.out.println("尾插入"); + } + + public void testInsertFromHead() throws Exception { +// linkList.insertFromHead(1); +// linkList.insertFromHead(2); +// linkList.insertFromHead(3); +// linkList.insertFromHead(4); +// linkList.insertFromHead(5); +// linkList.insertFromHead(6); +// System.out.println("头插入"); + } + public void testReverseLinkList() throws Exception { + System.out.println(); + linkList.insertFromHead(1); + linkList.insertFromHead(2); + linkList.insertFromHead(3); + linkList.insertFromHead(4); + linkList.insertFromHead(5); + linkList.insertFromHead(6); + linkList.printLinkList(linkList.reverseLinkList()); + } + + public void testReverseLinkList2() throws Exception{ + System.out.println("递归反转链表"); + linkList.insertFromHead(1); + linkList.insertFromHead(2); + linkList.insertFromHead(3); + linkList.insertFromHead(4); + linkList.insertFromHead(5); + linkList.insertFromHead(6); + linkList.printLinkList(linkList.reverseLinkList(linkList.getHead())); + } + public void testGetHead() throws Exception { + } + +} \ No newline at end of file diff --git a/src/test/java/cn/byhieg/algorithmtutorialtest/SortTest.java b/src/test/java/cn/byhieg/algorithmtutorialtest/SortTest.java new file mode 100644 index 0000000..046daca --- /dev/null +++ b/src/test/java/cn/byhieg/algorithmtutorialtest/SortTest.java @@ -0,0 +1,53 @@ +package cn.byhieg.algorithmtutorialtest; + +import cn.byhieg.algorithmtutorial.Sort; +import junit.framework.TestCase; + +/** + * Created by shiqifeng on 2017/3/28. + * Mail byhieg@gmail.com + */ +public class SortTest extends TestCase { + int [] nums; + public void setUp() throws Exception { + super.setUp(); + nums = new int[]{10, 20, 2, 3, 1, 100, 45, 22, 51, 21}; + } + + public void tearDown() throws Exception { + for (int i = 0 ; i < nums.length;i++){ + System.out.print(nums[i] + " "); + } + } +// +// public void testChooseSort() throws Exception { +// new Sort().chooseSort(nums); +// } +// +// +// public void testInsertDirectlySort() throws Exception { +// new Sort().insertDirectlySort(nums); +// } +// +// public void testInsertBinarySort() throws Exception { +// new Sort().insertBinarySort(nums); +// } +// +// public void testBubbleSort() throws Exception { +// new Sort().bubbleSort2(nums); +// } +// +// public void testQuickSort() throws Exception { +// new Sort().quickSort(nums); +// } + +// public void testHeapSort() throws Exception { +// new Sort().heapSort(nums); +// } + + public void testMergeSort() throws Exception { + new Sort().mergeSort(nums); + + } + +} \ No newline at end of file diff --git a/src/test/java/cn/byhieg/bitoperatetutorialtest/BitOperateTest.java b/src/test/java/cn/byhieg/bitoperatetutorialtest/BitOperateTest.java new file mode 100644 index 0000000..962eccd --- /dev/null +++ b/src/test/java/cn/byhieg/bitoperatetutorialtest/BitOperateTest.java @@ -0,0 +1,23 @@ +package cn.byhieg.bitoperatetutorialtest; + +import cn.byhieg.bitoperatetutorial.BitOperate; +import junit.framework.TestCase; + +/** + * Created by byhieg on 2017/6/27. + * Mail to byhieg@gmail.com + */ +public class BitOperateTest extends TestCase { + + BitOperate bitOperate; + @Override + protected void setUp() throws Exception { + super.setUp(); + bitOperate = new BitOperate(); + } + + public void testGetRightestOne() throws Exception { + assertEquals(bitOperate.getRightestOne(Integer.valueOf("100100",2)),"100"); + } + +} \ No newline at end of file diff --git a/src/test/java/cn/byhieg/collectiontutorialtest/BinarySearchTreeTest.java b/src/test/java/cn/byhieg/collectiontutorialtest/BinarySearchTreeTest.java new file mode 100644 index 0000000..c56ce25 --- /dev/null +++ b/src/test/java/cn/byhieg/collectiontutorialtest/BinarySearchTreeTest.java @@ -0,0 +1,64 @@ +package cn.byhieg.collectiontutorialtest; + +import cn.byhieg.algorithmtutorial.BinarySearchTree; +import junit.framework.TestCase; +import org.junit.Assert; + +/** + * Created by byhieg on 17/3/30. + * Mail to byhieg@gmail.com + */ +public class BinarySearchTreeTest extends TestCase { + int[] nums; + BinarySearchTree tree; + + public void setUp() throws Exception { + super.setUp(); + nums = new int[]{1,2,3,4,5}; + tree = new BinarySearchTree(nums); + } + + public void tearDown() throws Exception { + BinarySearchTree.Node node = new BinarySearchTree.Node(10); + tree.levelRead(node); + } + + + public void testInsert() throws Exception { + } + + public void testInOrder() throws Exception { + System.out.println("中序遍历"); + tree.inorder2(tree.getRoot()); + System.out.println(); + } + + public void testPreOrder() throws Exception { + System.out.println("先续遍历"); + tree.preOrder2(tree.getRoot()); + System.out.println(); + } + + public void testPostOrder() throws Exception { + System.out.println("后续遍历"); + tree.postOrder2(tree.getRoot()); + System.out.println(); + } + + public void testGetTree() throws Exception { + System.out.println("树"); + int[] pre = new int[]{1,2,4,5,3}; + int[] in = new int[]{4,2,5,1,3}; + BinarySearchTree.Node node = new BinarySearchTree.Node(1); + tree.getTree(pre, in,node); + tree.levelRead(node); + } + +// public void testGetMaxData() throws Exception { +// Assert.assertEquals(10,tree.getMaxNode().data); +// } +// +// public void testGetMinData() throws Exception { +// Assert.assertEquals(1,tree.getMinNode().data); +// } +} \ No newline at end of file diff --git a/src/test/java/cn/byhieg/designpatterntutorialtest/BuilderTest.java b/src/test/java/cn/byhieg/designpatterntutorialtest/BuilderTest.java new file mode 100644 index 0000000..2a67a00 --- /dev/null +++ b/src/test/java/cn/byhieg/designpatterntutorialtest/BuilderTest.java @@ -0,0 +1,16 @@ +package cn.byhieg.designpatterntutorialtest; + +import cn.byhieg.designpatterntutorial.builder.Person; +import junit.framework.TestCase; + +/** + * Created by shiqifeng on 2017/5/7. + * Mail byhieg@gmail.com + */ +public class BuilderTest extends TestCase { + public void testBuild() throws Exception { + Person person = new Person.Builder().setAge(24).setHeight(178).setName("byhieg").setWeight(80).build(); + System.out.println(person.toString()); + } + +} \ No newline at end of file diff --git a/src/test/java/cn/byhieg/designpatterntutorialtest/SimpleDialogTest.java b/src/test/java/cn/byhieg/designpatterntutorialtest/SimpleDialogTest.java new file mode 100644 index 0000000..002115a --- /dev/null +++ b/src/test/java/cn/byhieg/designpatterntutorialtest/SimpleDialogTest.java @@ -0,0 +1,18 @@ +package cn.byhieg.designpatterntutorialtest; + +import cn.byhieg.designpatterntutorial.builder.SimpleDialog; +import junit.framework.TestCase; + +/** + * Created by shiqifeng on 2017/5/7. + * Mail byhieg@gmail.com + */ +public class SimpleDialogTest extends TestCase { + + public void testBuilder() throws Exception { + SimpleDialog dialog = new SimpleDialog.Builder().setIcon("图标").setMessage("这是Dialog").setPositiveButton("确认").setNegativeButton("否定").create(); + + + } + +} \ No newline at end of file diff --git a/src/test/java/cn/byhieg/threadtutorialtest/concurrenttest/atomtest/AtomFactoryTest.java b/src/test/java/cn/byhieg/threadtutorialtest/concurrenttest/atomtest/AtomFactoryTest.java new file mode 100644 index 0000000..e8b706a --- /dev/null +++ b/src/test/java/cn/byhieg/threadtutorialtest/concurrenttest/atomtest/AtomFactoryTest.java @@ -0,0 +1,82 @@ +package cn.byhieg.threadtutorialtest.concurrenttest.atomtest; + +import cn.byhieg.threadtutorial.concurrent.atom.AtomFactory; + +import cn.byhieg.threadtutorial.concurrent.atom.MyObject; +import junit.framework.TestCase; + +import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.atomic.AtomicIntegerArray; +import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; +import java.util.concurrent.atomic.AtomicReference; + +/** + * Created by shiqifeng on 2017/5/5. + * Mail byhieg@gmail.com + */ +public class AtomFactoryTest extends TestCase { + AtomicInteger integer; + AtomicIntegerArray array; + AtomicReference reference;
+ AtomicIntegerFieldUpdater updater;
+
+ public void setUp() throws Exception {
+ super.setUp();
+ integer = AtomFactory.getInstance().createAtomInt(1);
+ }
+
+ public void testAtomInt() throws Exception {
+ System.out.println("int原子类");
+ new Thread(()->{
+ for (int i = 0; i < 10; i++) { + integer.getAndIncrement(); + System.out.println(getName() + " " + integer.get()); + } + }).start(); + + new Thread(()->{
+ for (int i = 0; i < 10; i++) {
+ integer.getAndIncrement();
+ System.out.println(getName() + " " + integer.get());
+ }
+ }).start();
+
+ Thread.sleep(1000);
+ }
+
+ public void testAtomArray() throws Exception {
+ System.out.println("原子类数组");
+ int [] value = new int[]{1,2,3,4};
+ array = AtomFactory.getInstance().createAtomArray(value);
+ array.getAndSet(1,10);
+ System.out.println(array.get(1));
+ System.out.println(value[1]);
+ }
+
+ public void testAtomRef()throws Exception {
+ System.out.println("原子类");
+ MyObject object = new MyObject();
+ reference = AtomFactory.getInstance().createAtomReference(object);
+ reference.set(object);
+ MyObject newObject = new MyObject();
+ newObject.name = "xiaoli";
+ reference.compareAndSet(object, newObject);
+ System.out.println(reference.get().name);
+ }
+
+
+ public void testUpdater() throws Exception {
+ System.out.println("原子类更新字段");
+ updater = AtomFactory.getInstance().createAtomIntegerUpdate("id");
+ MyObject object = new MyObject();
+ System.out.println(updater.getAndIncrement(object));
+ System.out.println(updater.get(object));
+ }
+
+
+ public void tearDown() throws Exception {
+
+ }
+
+
+}
\ No newline at end of file
diff --git a/src/test/java/cn/byhieg/threadtutorialtest/concurrenttest/blockingtest/ArrayBlockTest.java b/src/test/java/cn/byhieg/threadtutorialtest/concurrenttest/blockingtest/ArrayBlockTest.java
new file mode 100644
index 0000000..c48566c
--- /dev/null
+++ b/src/test/java/cn/byhieg/threadtutorialtest/concurrenttest/blockingtest/ArrayBlockTest.java
@@ -0,0 +1,34 @@
+package cn.byhieg.threadtutorialtest.concurrenttest.blockingtest;
+
+import cn.byhieg.threadtutorial.concurrent.blocking.ArrayBlock;
+import cn.byhieg.threadtutorial.concurrent.blocking.Costumer;
+import cn.byhieg.threadtutorial.concurrent.blocking.Producer;
+import junit.framework.TestCase;
+
+import javax.swing.*;
+
+/**
+ * Created by byhieg on 17/5/3.
+ * Mail to byhieg@gmail.com
+ */
+public class ArrayBlockTest extends TestCase {
+ ArrayBlock block;
+ public void setUp() throws Exception {
+ super.setUp();
+ block = new ArrayBlock(2);
+ }
+
+ public void tearDown() throws Exception {
+ }
+
+
+ public void testBlocking() throws Exception {
+ Producer producer = new Producer(block);
+ Costumer costumer = new Costumer(block);
+ producer.start();
+ costumer.start();
+ producer.join();
+ costumer.join();
+
+ }
+}
\ No newline at end of file