From b7d36b8367f474f31c47400740edba410751a25f Mon Sep 17 00:00:00 2001 From: robert <805467553@qq.com> Date: Mon, 22 Nov 2021 17:14:02 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BB=A3=E7=A0=81=E5=AE=8C=E5=96=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .classpath | 20 -- .gitignore | 2 + .project | 23 -- .settings/org.eclipse.jdt.core.prefs | 13 - .settings/org.eclipse.m2e.core.prefs | 4 - pom.xml | 10 +- src/com/algorithm/list/MyLinkedList.java | 279 +++++++++--------- src/com/algorithm/list/ReverseList.java | 50 ++++ src/com/algorithm/sort/BellmanFord.java | 139 +++++++++ src/com/algorithm/sort/Dijkstra.java | 61 ++++ src/com/algorithm/sort/HeapSort.java | 65 +++++ src/com/algorithm/sort/MergeSort.java | 144 ++++++---- src/com/algorithm/sort/QuickSort.java | 130 +++++---- src/com/algorithm/tree/BinaryTree.java | 343 +++++++++++++---------- src/com/algorithm/tree/Heap.java | 2 +- 15 files changed, 831 insertions(+), 454 deletions(-) delete mode 100644 .classpath delete mode 100644 .project delete mode 100644 .settings/org.eclipse.jdt.core.prefs delete mode 100644 .settings/org.eclipse.m2e.core.prefs create mode 100644 src/com/algorithm/list/ReverseList.java create mode 100644 src/com/algorithm/sort/BellmanFord.java create mode 100644 src/com/algorithm/sort/Dijkstra.java create mode 100644 src/com/algorithm/sort/HeapSort.java diff --git a/.classpath b/.classpath deleted file mode 100644 index cb7d5bc..0000000 --- a/.classpath +++ /dev/null @@ -1,20 +0,0 @@ - - - - - - - - - - - - - - - - - - - - diff --git a/.gitignore b/.gitignore index 09e3bc9..474813f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,4 @@ /bin/ /target/ +.project +.settings/ \ No newline at end of file diff --git a/.project b/.project deleted file mode 100644 index 95d778d..0000000 --- a/.project +++ /dev/null @@ -1,23 +0,0 @@ - - - algorithm - - - - - - org.eclipse.jdt.core.javabuilder - - - - - org.eclipse.m2e.core.maven2Builder - - - - - - org.eclipse.m2e.core.maven2Nature - org.eclipse.jdt.core.javanature - - diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs deleted file mode 100644 index 9c4403f..0000000 --- a/.settings/org.eclipse.jdt.core.prefs +++ /dev/null @@ -1,13 +0,0 @@ -eclipse.preferences.version=1 -org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled -org.eclipse.jdt.core.compiler.codegen.methodParameters=do not generate -org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.7 -org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve -org.eclipse.jdt.core.compiler.compliance=1.7 -org.eclipse.jdt.core.compiler.debug.lineNumber=generate -org.eclipse.jdt.core.compiler.debug.localVariable=generate -org.eclipse.jdt.core.compiler.debug.sourceFile=generate -org.eclipse.jdt.core.compiler.problem.assertIdentifier=error -org.eclipse.jdt.core.compiler.problem.enumIdentifier=error -org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning -org.eclipse.jdt.core.compiler.source=1.7 diff --git a/.settings/org.eclipse.m2e.core.prefs b/.settings/org.eclipse.m2e.core.prefs deleted file mode 100644 index 14b697b..0000000 --- a/.settings/org.eclipse.m2e.core.prefs +++ /dev/null @@ -1,4 +0,0 @@ -activeProfiles= -eclipse.preferences.version=1 -resolveWorkspaceProjects=true -version=1 diff --git a/pom.xml b/pom.xml index dee84fb..a14056d 100644 --- a/pom.xml +++ b/pom.xml @@ -31,7 +31,15 @@ - + + org.apache.maven.plugins + maven-compiler-plugin + + 7 + 7 + + + diff --git a/src/com/algorithm/list/MyLinkedList.java b/src/com/algorithm/list/MyLinkedList.java index 1ec2fa0..62b8478 100644 --- a/src/com/algorithm/list/MyLinkedList.java +++ b/src/com/algorithm/list/MyLinkedList.java @@ -6,144 +6,151 @@ /** * 链表数据结构 - * - * @author chao * * @param + * @author chao */ public class MyLinkedList implements Iterable { - public static class Node { - public Node() { - - } - - public Node(T ele) { - this.ele = ele; - } - - public Node(T ele, Node next, Node pre) { - this.ele = ele; - this.next = next; - this.pre = pre; - } - - T ele; - Node next; - Node pre; - } - - private Node head; - private Node tail; - private int size; - private int modcount = 0; - - public MyLinkedList() { - clear(); - } - - public void clear() { - head = new Node(null, null, null); - tail = new Node(null, head, null); - head.next = tail; - size = 0; - modcount++; - - } - - @Override - public Iterator iterator() { - return new LinkedListIterator(); - } - - private class LinkedListIterator implements Iterator { - private Node current = head.next; - private boolean okToremove = false; - private int expectedModcount = modcount; - - @Override - public boolean hasNext() { - return current != tail; - } - - @Override - public E next() { - if (modcount != expectedModcount) { - throw new ConcurrentModificationException(); - } else if (!hasNext()) { - throw new NoSuchElementException(); - } - current = current.next; - okToremove = true; - return (E) current.pre.ele; - } - - @Override - public void remove() { - if (!okToremove) { - throw new IllegalStateException(); - } else if (modcount != expectedModcount) { - throw new ConcurrentModificationException(); - } - MyLinkedList.this.remove(current.pre); - okToremove = false; - expectedModcount++; - } - } - - public boolean isempty() { - return size == 0; - } - - public int size() { - return size; - } - - private Node getNode(int index) { - if (index < 0 || index >= size) { - throw new IndexOutOfBoundsException(); - } - Node p = null; - if (index < size / 2) { - p = head.next; - for (int i = 0; i < index; i++) - p = p.next; - } else { - p = tail; - for (int i = size; i > index; i--) - p = p.pre; - } - return p; - } - - public E get(int index) { - return (E) getNode(index).ele; - } - - private E remove(Node node) { - node.next.pre = node.pre; - node.pre.next = node.next; - size--; - modcount++; - return (E) node.ele; - } - - public E remove(int index) { - return remove(getNode(index)); - } - - public void add(int index, E ele) { - addBefore(getNode(index), ele); - } - - private void addBefore(Node node, E ele) { - Node newnode = new Node(ele, node.pre, node); - node.pre.next = newnode; - node.pre = newnode; - size++; - modcount++; - } - - public void add(E ele) { - add(size, ele); - } + + public static class Node { + public Node() { + + } + + public Node(T ele) { + this.ele = ele; + } + + public Node(T ele, Node next, Node pre) { + this.ele = ele; + this.next = next; + this.pre = pre; + } + + T ele; + Node next; + Node pre; + } + + private Node head; + private Node tail; + private int size; + private int modcount = 0; + + public MyLinkedList() { + clear(); + } + + public Node getHead() { + return head; + } + + public void clear() { + head = new Node<>(null, null, null); + tail = new Node<>(null, head, null); + head.next = tail; + size = 0; + modcount++; + + } + + @Override + public Iterator iterator() { + return new LinkedListIterator(); + } + + private class LinkedListIterator implements Iterator { + private Node current = head.next; + private boolean okToremove = false; + private int expectedModcount = modcount; + + @Override + public boolean hasNext() { + return current != tail; + } + + @Override + public E next() { + if (modcount != expectedModcount) { + throw new ConcurrentModificationException(); + } else if (!hasNext()) { + throw new NoSuchElementException(); + } + current = current.next; + okToremove = true; + return current.pre.ele; + } + + @Override + public void remove() { + if (!okToremove) { + throw new IllegalStateException(); + } else if (modcount != expectedModcount) { + throw new ConcurrentModificationException(); + } + MyLinkedList.this.remove(current.pre); + okToremove = false; + expectedModcount++; + } + } + + public boolean isEmpty() { + return size == 0; + } + + public int size() { + return size; + } + + private Node getNode(int index) { + if (index == 0) { + return head; + } + if (index < 0 || index >= size) { + throw new IndexOutOfBoundsException(); + } + Node p = null; + if (index < size / 2) { + p = head.next; + for (int i = 0; i < index; i++) + p = p.next; + } else { + p = tail; + for (int i = size; i > index; i--) + p = p.pre; + } + return p; + } + + public E get(int index) { + return (E) getNode(index).ele; + } + + private E remove(Node node) { + node.next.pre = node.pre; + node.pre.next = node.next; + size--; + modcount++; + return (E) node.ele; + } + + public E remove(int index) { + return remove(getNode(index)); + } + + public void add(int index, E ele) { + addBefore(getNode(index), ele); + } + + private void addBefore(Node node, E ele) { + Node newnode = new Node(ele, node.pre, node); + node.pre.next = newnode; + node.pre = newnode; + size++; + modcount++; + } + + public void add(E ele) { + add(size, ele); + } } \ No newline at end of file diff --git a/src/com/algorithm/list/ReverseList.java b/src/com/algorithm/list/ReverseList.java new file mode 100644 index 0000000..cc071ee --- /dev/null +++ b/src/com/algorithm/list/ReverseList.java @@ -0,0 +1,50 @@ +package com.algorithm.list; + +public class ReverseList { + + public static void main(String args[]) { + MyLinkedList.Node head = new MyLinkedList.Node(1); + head.next = new MyLinkedList.Node(2); + head.next.next = new MyLinkedList.Node(3); + + MyLinkedList.Node node = reverse3(head); + for (; node != null; node = node.next) { + System.out.println(node.ele); + } + } + + public static MyLinkedList.Node reverse(MyLinkedList.Node head) { + MyLinkedList.Node pre = null; + MyLinkedList.Node cur = head; + MyLinkedList.Node next; + + while (cur != null) { + next = cur.next; + cur.next = pre; + pre = cur; + cur = next; + } + return pre; + } + + public static MyLinkedList.Node reverse2(MyLinkedList.Node head) { + if (head == null || head.next == null) { + return head; + } + MyLinkedList.Node newHead = reverse2(head.next); + head.next.next = head; + head.next = null; + return newHead; + } + + public static MyLinkedList.Node reverse3(MyLinkedList.Node head) { + MyLinkedList.Node newHead = null; + while (head != null) { + MyLinkedList.Node next = head.next; + head.next=newHead; + newHead=head; + head = next; + } + return newHead; + } +} diff --git a/src/com/algorithm/sort/BellmanFord.java b/src/com/algorithm/sort/BellmanFord.java new file mode 100644 index 0000000..2b9020a --- /dev/null +++ b/src/com/algorithm/sort/BellmanFord.java @@ -0,0 +1,139 @@ +package com.algorithm.sort; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; + +public class BellmanFord { + + /** + * 实现思路: + * 1、初始化时将起点起点到各个顶点的距离赋值为(无穷大)∞,当前起点距离赋值为0 + * 2、后续进行最多n-1次遍历操作 + * + * @param args + */ + public static void main(String[] args) { + + //创建图 + Edge ab = new Edge("A", "B", -1); + Edge ac = new Edge("A", "C", 4); + Edge bc = new Edge("B", "C", 3); + Edge be = new Edge("B", "E", 2); + Edge ed = new Edge("E", "D", -3); + Edge dc = new Edge("D", "C", 5); + Edge bd = new Edge("B", "D", 2); + Edge db = new Edge("D", "B", 1); + + //需要按图中的步骤步数顺序建立数组,否则就是另外一幅图了, + //从起点A出发,步骤少的排前面 + Edge[] edges = new Edge[]{ab, ac, bc, be, bd, ed, dc, db}; + + //存放到各个节点所需要消耗的时间 + HashMap costMap = new HashMap(); + //到各个节点对应的父节点 + HashMap parentMap = new HashMap(); + + + //初始化各个节点所消费的,当然也可以再遍历的时候判断下是否为Null + //i=0的时候 + costMap.put("A", 0); //源点 + costMap.put("B", Integer.MAX_VALUE); + costMap.put("C", Integer.MAX_VALUE); + costMap.put("D", Integer.MAX_VALUE); + costMap.put("E", Integer.MAX_VALUE); + + //进行节点数n-1次循环 + for (int i = 1; i < costMap.size(); i++) { + boolean hasChange = false; + for (int j = 0; j < edges.length; j++) { + Edge edge = edges[j]; + //该边起点目前总的路径大小 + int startPointCost = costMap.get(edge.getStartPoint()) == null ? 0 : costMap.get(edge.getStartPoint()); + //该边终点目前总的路径大小 + int endPointCost = costMap.get(edge.getEndPoint()) == null ? Integer.MAX_VALUE : costMap.get(edge.getEndPoint()); + //如果该边终点目前的路径大小 > 该边起点的路径大小 + 该边权重 ,说明有更短的路径了 + if (endPointCost > (startPointCost + edge.getWeight())) { + costMap.put(edge.getEndPoint(), startPointCost + edge.getWeight()); + parentMap.put(edge.getEndPoint(), edge.getStartPoint()); + hasChange = true; + } + } + if (!hasChange) { + //经常还没达到最大遍历次数便已经求出解了,此时可以优化为提前退出循环 + break; + } + } + + //在进行一次判断是否存在负环路 + boolean hasRing = false; + for (int j = 0; j < edges.length; j++) { + Edge edge = edges[j]; + int startPointCost = costMap.get(edge.getStartPoint()) == null ? 0 : costMap.get(edge.getStartPoint()); + int endPointCost = costMap.get(edge.getEndPoint()) == null ? Integer.MAX_VALUE : costMap.get(edge.getEndPoint()); + if (endPointCost > (startPointCost + edge.getWeight())) { + System.out.print("\n图中存在负环路,无法求解\n"); + hasRing = true; + break; + } + } + + if (!hasRing) { + //打印出到各个节点的最短路径 + for (String key : costMap.keySet()) { + System.out.print("\n到目标节点" + key + "最低耗费:" + costMap.get(key)); + if (parentMap.containsKey(key)) { + List pathList = new ArrayList(); + String parentKey = parentMap.get(key); + while (parentKey != null) { + pathList.add(0, parentKey); + parentKey = parentMap.get(parentKey); + } + pathList.add(key); + String path = ""; + for (String k : pathList) { + path = path.equals("") ? path : path + " --> "; + path = path + k; + } + System.out.print(",路线为" + path); + } + } + } + + + } + + + /** + * 代表"一条边"的信息对象 + * + * @author Administrator + */ + static class Edge { + //起点id + private String startPoint; + //结束点id + private String endPoint; + //该边的权重 + private int weight; + + public Edge(String startPoint, String endPoint, int weight) { + this.startPoint = startPoint; + this.endPoint = endPoint; + this.weight = weight; + } + + public String getStartPoint() { + return startPoint; + } + + public String getEndPoint() { + return endPoint; + } + + public int getWeight() { + return weight; + } + } + +} \ No newline at end of file diff --git a/src/com/algorithm/sort/Dijkstra.java b/src/com/algorithm/sort/Dijkstra.java new file mode 100644 index 0000000..76c53f2 --- /dev/null +++ b/src/com/algorithm/sort/Dijkstra.java @@ -0,0 +1,61 @@ +package com.algorithm.sort; + +import java.util.Arrays; + +public class Dijkstra { + + static int[][] map; + + static int[] distance; + + static boolean[] visited; + + public static void dijkstra(int beginIndex) { + int nodeNum = map.length - 1; + distance[beginIndex] = 0; + // 所有结点都要访问一次,共nodeNum次 + // 第一次从beginIndex的结点开始 + // 然后每次从未访问过、并且可以访问的最近的结点开始 + for (int i = 0; i < nodeNum; i++) { + int index = beginIndex;// index代表当前结点的下标 + int minDistance = Integer.MAX_VALUE;// minDistance代表起点到当前结点的最短距离 + for (int j = 1; j <= nodeNum; j++) { + if (distance[j] < minDistance && !visited[j]) { + index = j; + minDistance = distance[j]; + } + } + + for (int j = 1; j <= nodeNum; j++) { + if (map[index][j] != 0 && minDistance + map[index][j] < distance[j]) { + distance[j] = minDistance + map[index][j]; + } + } + System.err.println(Arrays.toString(distance)); + visited[index] = true; + } + } + + public static void initResources() { + map = new int[7][7]; + map[1][2] = 1; + map[1][3] = 12; + map[2][3] = 9; + map[2][4] = 3; + map[3][5] = 5; + map[4][3] = 4; + map[4][5] = 13; + map[4][6] = 15; + map[5][6] = 4; + distance = new int[7]; + for (int i = 0; i < 7; i++) distance[i] = Integer.MAX_VALUE; + visited = new boolean[7]; + } + + public static void main(String[] args) { + initResources(); + dijkstra(1); + System.err.println(Arrays.toString(distance)); + } + +} \ No newline at end of file diff --git a/src/com/algorithm/sort/HeapSort.java b/src/com/algorithm/sort/HeapSort.java new file mode 100644 index 0000000..26219d8 --- /dev/null +++ b/src/com/algorithm/sort/HeapSort.java @@ -0,0 +1,65 @@ +package com.algorithm.sort; + +import java.util.Arrays; + +/** + * Created by chengxiao on 2016/12/17. + * 堆排序demo + */ +public class HeapSort { + public static void main(String[] args) { + int[] arr = {1, 2, 3, 6, 5, 4, 9, 8, 7}; + sort(arr); + System.out.println(Arrays.toString(arr)); + } + + public static void sort(int[] arr) { + //1.构建大顶堆 + for (int i = arr.length / 2 - 1; i >= 0; i--) { + //从第一个非叶子结点从下至上,从右至左调整结构 + adjustHeap(arr, i, arr.length); + } + //2.调整堆结构+交换堆顶元素与末尾元素 + for (int j = arr.length - 1; j > 0; j--) { + swap(arr, 0, j);//将堆顶元素与末尾元素进行交换 + adjustHeap(arr, 0, j);//重新对堆进行调整 + } + + } + + /** + * 调整大顶堆(仅是调整过程,建立在大顶堆已构建的基础上) + * + * @param arr + * @param i + * @param length + */ + public static void adjustHeap(int[] arr, int i, int length) { + int temp = arr[i];//先取出当前元素i + for (int k = i * 2 + 1; k < length; k = k * 2 + 1) {//从i结点的左子结点开始,也就是2i+1处开始 + if (k + 1 < length && arr[k] < arr[k + 1]) {//如果左子结点小于右子结点,k指向右子结点 + k++; + } + if (arr[k] > temp) {//如果子节点大于父节点,将子节点值赋给父节点(不用进行交换) + arr[i] = arr[k]; + i = k; + } else { + break; + } + } + arr[i] = temp;//将temp值放到最终的位置 + } + + /** + * 交换元素 + * + * @param arr + * @param a + * @param b + */ + public static void swap(int[] arr, int a, int b) { + int temp = arr[a]; + arr[a] = arr[b]; + arr[b] = temp; + } +} \ No newline at end of file diff --git a/src/com/algorithm/sort/MergeSort.java b/src/com/algorithm/sort/MergeSort.java index 53fd5ff..c3d1460 100644 --- a/src/com/algorithm/sort/MergeSort.java +++ b/src/com/algorithm/sort/MergeSort.java @@ -2,70 +2,96 @@ /** * 归并排序 - * - * @author chao * + * @author chao */ public class MergeSort { - /** - * 归并排序 - * - * @param num - * @param start - * @param end - */ - public static void sort(int num[], int start, int end) { - if (start >= end) { - return; - } - int mid = (start + end) / 2; - sort(num, start, mid); - sort(num, mid + 1, end); - merge(num, start, mid, end); + /** + * 归并排序 + * + * @param num + * @param start + * @param end + */ + public static void sort(int num[], int start, int end) { + if (start >= end) { + return; + } + int mid = (start + end) / 2; + sort(num, start, mid); + sort(num, mid + 1, end); + merge(num, start, mid, end); + + } - } + /** + * num[start]到num[mid]是有序的,num[mid+1]到num[end]是有序的, + * 重新合并数组,使数组num[start]到num[end]有序 + * + * @param num + * @param start + * @param mid + * @param end + */ + public static void merge1(int[] num, int start, int mid, int end) { + int[] num1 = new int[mid - start + 1]; + int[] num2 = new int[end - mid]; + int i, j, k; + for (i = start; i <= end; i++) { + if (i - start < num1.length) { + num1[i - start] = num[i]; + } else { + num2[i - start - num1.length] = num[i]; + } + } + i = j = k = 0; + while (i < num1.length && j < num2.length) { + if (num1[i] <= num2[j]) { + num[start + k++] = num1[i++]; + } else { + num[start + k++] = num2[j++]; + } + } - /** - * num[start]到num[mid]是有序的,num[mid+1]到num[end]是有序的, - * 重新合并数组,使数组num[start]到num[end]有序 - * - * @param num - * @param start - * @param mid - * @param end - */ - public static void merge(int[] num, int start, int mid, int end) { - int[] num1 = new int[mid - start + 1]; - int[] num2 = new int[end - mid]; - int i, j, k; - for (i = start; i <= end; i++) { - if (i - start < num1.length) { - num1[i - start] = num[i]; - } else { - num2[i - start - num1.length] = num[i]; - } - } - i = j = k = 0; - while (i < num1.length && j < num2.length) { - if (num1[i] <= num2[j]) { - num[start + k++] = num1[i++]; - } else { - num[start + k++] = num2[j++]; - } - } + while (i < num1.length) { + num[start + k++] = num1[i++]; + } + while (j < num2.length) { + num[start + k++] = num2[j++]; + } + } - while (i < num1.length) { - num[start + k++] = num1[i++]; - } - while (j < num2.length) { - num[start + k++] = num2[j++]; - } - } + public static void merge(int[] a, int low, int mid, int high) { + int[] temp = new int[high - low + 1]; + int i = low; + int j = mid + 1; + int k = 0; + // 把较小的数先移到新数组中 + while (i <= mid && j <= high) { + if (a[i] < a[j]) { + temp[k++] = a[i++]; + } else { + temp[k++] = a[j++]; + } + } + // 把左边剩余的数移入数组 + while (i <= mid) { + temp[k++] = a[i++]; + } + // 把右边边剩余的数移入数组 + while (j <= high) { + temp[k++] = a[j++]; + } + // 把新数组中的数覆盖a数组 + for (int x = 0; x < temp.length; x++) { + a[x + low] = temp[x]; + } + } - public static void main(String[] args) { - int[] num = { 1, 5, 3, 2 }; - sort(num, 0, num.length - 1); - for (int i = 0; i < num.length; i++) - System.out.print(num[i] + " "); - } + public static void main(String[] args) { + int[] num = {1, 5, 3, 2}; + sort(num, 0, num.length - 1); + for (int i = 0; i < num.length; i++) + System.out.print(num[i] + " "); + } } diff --git a/src/com/algorithm/sort/QuickSort.java b/src/com/algorithm/sort/QuickSort.java index 976e170..9cbdb5c 100644 --- a/src/com/algorithm/sort/QuickSort.java +++ b/src/com/algorithm/sort/QuickSort.java @@ -2,55 +2,91 @@ /** * 快速排序 - * - * @author chao * + * @author chao */ public class QuickSort { - /** - * 快速排序 - * - * @param num - * @param left - * @param right - */ - public static void sort(int[] num, int left, int right) { - if (left < right) { - int dp = partition(num, left, right); - sort(num, left, dp - 1); - sort(num, dp + 1, right); - } - } - - /** - * 数据分组 - * - * @param num - * @param left - * @param right - */ - public static int partition(int[] num, int left, int right) { - int pivot = num[left]; - while (left < right) { - while (left < right && num[right] >= pivot) - right--; - if (left < right) - num[left++] = num[right]; - while (left < right && num[left] <= pivot) - left++; - if (left < right) - num[right--] = num[left]; - } - num[left] = pivot; - return left; - } - - public static void main(String[] args) { - int[] num = { 1, 5, 3, 2 }; - sort(num, 0, num.length - 1); - for (int i = 0; i < num.length; i++) - System.out.print(num[i] + " "); - - } + /** + * 快速排序 + * + * @param num + * @param left + * @param right + */ + public static void sort(int[] num, int left, int right) { + if (left < right) { + int dp = partition(num, left, right); + sort(num, left, dp - 1); + sort(num, dp + 1, right); + } + } + + /** + * 数据分组 + * + * @param num + * @param left + * @param right + */ + public static int partition(int[] num, int left, int right) { + int pivot = num[left]; + while (left < right) { + while (left < right && num[right] >= pivot) + right--; + if (left < right) + num[left++] = num[right]; + while (left < right && num[left] <= pivot) + left++; + if (left < right) + num[right--] = num[left]; + } + num[left] = pivot; + + return left; + } + + public static void sortQ(int[] array, int left, int right) { + if (left > right) { + return; + } + // base中存放基准数 + int base = array[left]; + int i = left, j = right; + while (i != j) { + // 顺序很重要,先从右边开始往左找,直到找到比base值小的数 + while (array[j] >= base && i < j) { + j--; + } + + // 再从左往右边找,直到找到比base值大的数 + while (array[i] <= base && i < j) { + i++; + } + + // 上面的循环结束表示找到了位置或者(i>=j)了,交换两个数在数组中的位置 + if (i < j) { + int tmp = array[i]; + array[i] = array[j]; + array[j] = tmp; + } + } + + // 将基准数放到中间的位置(基准数归位) + array[left] = array[i]; + array[i] = base; + + // 递归,继续向基准的左右两边执行和上面同样的操作 + // i的索引处为上面已确定好的基准值的位置,无需再处理 + sortQ(array, left, i - 1); + sortQ(array, i + 1, right); + } + + public static void main(String[] args) { + int[] num = {2, 5, 3, 1}; + sort(num, 0, num.length - 1); + for (int i = 0; i < num.length; i++) + System.out.print(num[i] + " "); + + } } diff --git a/src/com/algorithm/tree/BinaryTree.java b/src/com/algorithm/tree/BinaryTree.java index eecb0b2..fae165f 100644 --- a/src/com/algorithm/tree/BinaryTree.java +++ b/src/com/algorithm/tree/BinaryTree.java @@ -1,162 +1,205 @@ package com.algorithm.tree; import java.util.ArrayDeque; +import java.util.LinkedList; import java.util.Queue; +import java.util.Stack; /** * 二叉树 - * - * @author chao * * @param + * @author chao */ public class BinaryTree { - protected BinaryTreeNode root; - - protected static class BinaryTreeNode { - protected T element; - protected BinaryTreeNode left; - protected BinaryTreeNode right; - protected int hintcount; - - public BinaryTreeNode(T element) { - this(element, null, null); - } - - public BinaryTreeNode(T element, BinaryTreeNode left, BinaryTreeNode right) { - this.element = element; - this.right = right; - this.left = left; - } - } - - public BinaryTree(T root) { - if (root != null) { - this.root = new BinaryTreeNode(root); - } - - } - - public BinaryTreeNode getRoot() { - return root; - } - - public void inOrderTraversal() { - inOrderTraversal(root); - } - - /** - * 中序遍历LDR - */ - protected void inOrderTraversal(BinaryTreeNode node) { - if (node == null) { - return; - } else { - inOrderTraversal(node.left); - printNode(node); - inOrderTraversal(node.right); - } - } - - public void firstOrderTraversal() { - firstOrderTraversal(root); - } - - /** - * 先序遍历DLR - */ - protected void firstOrderTraversal(BinaryTreeNode node) { - if (node == null) { - return; - } else { - printNode(node); - firstOrderTraversal(node.left); - firstOrderTraversal(node.right); - } - } - - public void lastOrderTraversal() { - lastOrderTraversal(root); - } - - /** - * 后序遍历LRD - */ - protected void lastOrderTraversal(BinaryTreeNode node) { - if (node == null) { - return; - } else { - lastOrderTraversal(node.left); - lastOrderTraversal(node.right); - for (int i = -1; i < node.hintcount; i++) { - System.out.print(" " + node.element + " "); - } - } - } - - public int getWidth() { - return getWidth(root); - } - - /** - * 某个节点下的最大宽度 - * - * @param node - * @return - */ - protected int getWidth(BinaryTreeNode node) { - if (node == null) - return 0; - - Queue> queue = new ArrayDeque<>(); - int maxWitdth = 1; // 最大宽度 - queue.add(node); // 入队 - - while (true) { - int len = queue.size(); // 当前层的节点个数 - if (len == 0) - break; - while (len > 0) {// 如果当前层,还有节点 - BinaryTreeNode t = queue.poll(); - len--; - if (t.left != null) - queue.add(t.left); // 下一层节点入队 - if (t.right != null) - queue.add(t.right);// 下一层节点入队 - } - maxWitdth = Math.max(maxWitdth, queue.size()); - } - return maxWitdth; - } - - public int getHeight() { - return getHeight(root); - } - - /** - * 节点深度 - * - * @param node - * @return - */ - protected int getHeight(BinaryTreeNode node) { - if (node == null) - return 0; - else { - int left = getHeight(node.left); - int right = getHeight(node.right); - return 1 + Math.max(left, right); - } - } - - /** - * 打印结点信息 - * - * @param node - */ - protected void printNode(BinaryTreeNode node) { - for (int i = -1; i < node.hintcount; i++) { - System.out.print(" " + node.element + " "); - } - } + protected BinaryTreeNode root; + + protected static class BinaryTreeNode { + protected T element; + protected BinaryTreeNode left; + protected BinaryTreeNode right; + protected int hintcount; + + public BinaryTreeNode(T element) { + this(element, null, null); + } + + public BinaryTreeNode(T element, BinaryTreeNode left, BinaryTreeNode right) { + this.element = element; + this.right = right; + this.left = left; + } + } + + public BinaryTree(T root) { + if (root != null) { + this.root = new BinaryTreeNode(root); + } + + } + + public BinaryTreeNode getRoot() { + return root; + } + + public void inOrderTraversal() { + inOrderTraversal(root); + } + + /** + * 中序遍历LDR + */ + protected void inOrderTraversal(BinaryTreeNode node) { + if (node == null) { + return; + } else { + inOrderTraversal(node.left); + printNode(node); + inOrderTraversal(node.right); + } + } + + //按照层次遍历二叉树 + public void levelTraversal(BinaryTreeNode root) { + if (root == null) { + return; + } + + Queue queue = new LinkedList<>(); + + queue.add(root); + + while (!queue.isEmpty()) { + BinaryTreeNode current = queue.remove(); + printNode(current); + if (current.left != null) { + queue.add(current.left); + } + + if (current.right != null) { + queue.add(current.right); + } + } + + } + + /** + * 非递归中序遍历LDR + */ + protected void inOrderTraversal2(BinaryTreeNode node) { + Stack stack = new Stack<>(); + BinaryTreeNode p = node; + while (p != null || !stack.isEmpty()) { + if (p != null) { + stack.push(p); + p = p.left; + } else { + p = stack.pop(); + printNode(p); + p = p.right; + } + } + } + + public void firstOrderTraversal() { + firstOrderTraversal(root); + } + + /** + * 先序遍历DLR + */ + protected void firstOrderTraversal(BinaryTreeNode node) { + if (node == null) { + return; + } else { + printNode(node); + firstOrderTraversal(node.left); + firstOrderTraversal(node.right); + } + } + + public void lastOrderTraversal() { + lastOrderTraversal(root); + } + + /** + * 后序遍历LRD + */ + protected void lastOrderTraversal(BinaryTreeNode node) { + if (node == null) { + return; + } else { + lastOrderTraversal(node.left); + lastOrderTraversal(node.right); + for (int i = -1; i < node.hintcount; i++) { + System.out.print(" " + node.element + " "); + } + } + } + + public int getWidth() { + return getWidth(root); + } + + /** + * 某个节点下的最大宽度 + * + * @param node + * @return + */ + protected int getWidth(BinaryTreeNode node) { + if (node == null) + return 0; + + Queue> queue = new ArrayDeque<>(); + int maxWitdth = 1; // 最大宽度 + queue.add(node); // 入队 + + while (true) { + int len = queue.size(); // 当前层的节点个数 + if (len == 0) + break; + while (len > 0) {// 如果当前层,还有节点 + BinaryTreeNode t = queue.poll(); + len--; + if (t.left != null) + queue.add(t.left); // 下一层节点入队 + if (t.right != null) + queue.add(t.right);// 下一层节点入队 + } + maxWitdth = Math.max(maxWitdth, queue.size()); + } + return maxWitdth; + } + + public int getHeight() { + return getHeight(root); + } + + /** + * 节点深度 + * + * @param node + * @return + */ + protected int getHeight(BinaryTreeNode node) { + if (node == null) + return 0; + else { + int left = getHeight(node.left); + int right = getHeight(node.right); + return 1 + Math.max(left, right); + } + } + + /** + * 打印结点信息 + * + * @param node + */ + protected void printNode(BinaryTreeNode node) { + for (int i = -1; i < node.hintcount; i++) { + System.out.print(" " + node.element + " "); + } + } } diff --git a/src/com/algorithm/tree/Heap.java b/src/com/algorithm/tree/Heap.java index eb16188..a05f96c 100644 --- a/src/com/algorithm/tree/Heap.java +++ b/src/com/algorithm/tree/Heap.java @@ -157,7 +157,7 @@ public static void heapUp(List heap, int index) { // 非递归实现 public static void heapUp2(List heap, int index) { - int parent = 0; + int parent; for (; index > 1; index /= 2) { // 获取index的父节点的下标 parent = index / 2;