1.稀疏数组
public class SparseArray {
public static void main(String[] args) {
int[][] charArray = new int[11][11];
charArray[1][2] = 1;
charArray[2][3] = 2;
System.out.println("原始的二维数组:");
for (int[] row : charArray) {
for(int data : row){
System.out.printf("%d\t", data);
}
System.out.println();
}
int sum = 0;
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if(charArray[i][j] != 0){
sum++;
}
}
}
int[][] sparseArr = new int[sum + 1][3];
sparseArr[0][0] = 11;
sparseArr[0][1] = 11;
sparseArr[0][2] = sum;
int count = 0;
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if(charArray[i][j] != 0){
count++;
sparseArr[count][0] = i;
sparseArr[count][1] = j;
sparseArr[count][2] = charArray[i][j];
}
}
}
System.out.println();
System.out.println("转换后的稀疏数组为:");
for (int i = 0; i < sparseArr.length; i++) {
System.out.printf("%d\t%d\t%d\t\n", sparseArr[i][0], sparseArr[i][1], sparseArr[i][2]);
}
System.out.println();
int[][] charArray2 = new int[sparseArr[0][0]][sparseArr[0][1]];
for (int i = 1; i < sparseArr.length; i++) {
charArray2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
}
System.out.println("恢复后的二维数组:");
for (int[] row : charArray2) {
for(int data : row){
System.out.printf("%d\t", data);
}
System.out.println();
}
}
}
2.队列
import java.util.Scanner;
public class ArrayQueue {
public static void main(String[] args) {
Queue queue = new Queue(3);
char key = ' ';
Scanner scanner = new Scanner(System.in);
boolean loop = true;
while(loop){
System.out.println("s:显示队列");
System.out.println("a:添加数据");
System.out.println("g:取出数据");
System.out.println("h:查头数据");
System.out.println("e:退出程序");
key = scanner.next().charAt(0);
switch (key) {
case 's':
queue.showQueue();
break;
case 'a':
System.out.println("请输入一个数:");
int value = scanner.nextInt();
queue.addQueue(value);
break;
case 'g':
try {
int res = queue.getQueue();
System.out.printf("取出的数据是:%d", res);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'h':
try {
int head = queue.headQueue();
System.out.printf("队列的头数据是:%d", head);
} catch (Exception e) {
System.out.println(e.getMessage());
}
break;
case 'e':
scanner.close();
loop = false;
break;
default:
break;
}
System.out.println("程序退出!");
}
}
}
class Queue{
private int maxSize;
private int front;
private int rear;
private int[] arr;
public Queue(int arrMaxSize){
maxSize = arrMaxSize;
arr = new int[arrMaxSize];
front = 0;
rear = 0;
}
public boolean isFull(){
return (rear + 1) % maxSize == front;
}
public boolean isEmpty(){
return rear == front;
}
public void addQueue(int n){
if(isFull()){
System.out.println("队列满了..");
return;
}
arr[rear] = n;
rear = (rear + 1) % maxSize;
}
public int getQueue(){
if(isEmpty()){
throw new RuntimeException("队列空,不能取数据");
}
int value = arr[front];
front = (front + 1) % maxSize;
return value;
}
public void showQueue(){
if(isEmpty()){
System.out.println("队列为空...");
return;
}
for (int i = front; i < front + size(); i++) {
System.out.printf("arr[%d]=%d\n", i % maxSize, arr[i % maxSize]);
}
}
public int size(){
return (rear + maxSize - front) % maxSize;
}
public int headQueue(){
if(isEmpty()){
throw new RuntimeException("队列为空...");
}
return arr[front];
}
}
3.链表
3.1单向链表
public class SingleLinkedList {
public static void main(String[] args) {
HeroNode hero1 = new HeroNode(1, "宋江", "及时雨");
HeroNode hero2 = new HeroNode(2, "卢俊义", "玉麒麟");
HeroNode hero3 = new HeroNode(3, "吴用", "智多星");
HeroNode hero4 = new HeroNode(4, "林冲", "豹子头");
LinkedList linkedList = new LinkedList();
linkedList.add(hero1);
linkedList.add(hero2);
linkedList.add(hero3);
linkedList.add(hero4);
linkedList.list();
}
}
class LinkedList{
private HeroNode head = new HeroNode(0, "", "");
private HeroNode tail = head;
public void add(HeroNode heroNode){
tail.next = heroNode;
tail = tail.next;
}
public void addByOrder(HeroNode heroNode){
HeroNode temp = head;
boolean flag = false;
while(true){
if(temp.next == null){
break;
}
if(temp.next.no > heroNode.no){
break;
}else if(temp.next.no == heroNode.no){
flag = true;
break;
}
temp = temp.next;
}
if(flag){
System.out.printf("准备插入的英雄编号%d已经存在了", heroNode.no);
}else{
heroNode.next = temp.next;
temp.next = heroNode;
}
}
public void list(){
if(head.next == null){
System.out.println("俩表为空");
return;
}
HeroNode temp = head.next;
while(true){
if(temp == null){
break;
}
System.out.println(temp);
temp = temp.next;
}
}
public void update(HeroNode heroNode){
if(head.next == null){
System.out.println("链表为空..");
return;
}
HeroNode temp = head.next;
boolean flag = false;
while(true){
if(temp == null){
break;
}
if(temp.no == heroNode.no){
flag = true;
break;
}
temp = temp.next;
}
if(flag){
temp.name = heroNode.name;
temp.nickName = heroNode.nickName;
}else{
System.out.printf("未找到该编号%d", heroNode.no);
}
}
public void delete(int no){
HeroNode temp = head;
boolean flag = false;
while(true){
if(temp.next == null){
break;
}
if(temp.next.no == no){
flag = true;
break;
}
temp = temp.next;
}
if(flag){
temp.next = temp.next.next;
}else{
System.out.printf("在链表中不存在编号%d", no);
}
}
}
class HeroNode{
public int no;
public String name;
public String nickName;
public HeroNode next;
public HeroNode(int no, String name, String nickName){
this.no = no;
this.name = name;
this.nickName = nickName;
}
@Override
public String toString() {
return "HeroNode[no=" + no + ",name=" + name + ",nickName=" + nickName + "]";
}
}
3.2双向链表
public class DoubleLinkedList {
public static void main(String[] args) {
HeroNode hero1 = new HeroNode(1, "宋江", "及时雨");
HeroNode hero2 = new HeroNode(2, "卢俊义", "玉麒麟");
HeroNode hero3 = new HeroNode(3, "吴用", "智多星");
HeroNode hero4 = new HeroNode(4, "林冲", "豹子头");
LinkedList linkedList = new LinkedList();
linkedList.add(hero1);
linkedList.add(hero2);
linkedList.add(hero3);
linkedList.add(hero4);
linkedList.list();
}
}
class LinkedList{
private HeroNode head = new HeroNode(0, "", "");
private HeroNode tail = head;
public void add(HeroNode heroNode){
tail.next = heroNode;
heroNode.pre = tail;
}
public void list(){
if(head.next == null){
System.out.println("俩表为空");
return;
}
HeroNode temp = head.next;
while(true){
if(temp == null){
break;
}
System.out.println(temp);
temp = temp.next;
}
}
public void update(HeroNode heroNode){
if(head.next == null){
System.out.println("链表为空..");
return;
}
HeroNode temp = head.next;
boolean flag = false;
while(true){
if(temp == null){
break;
}
if(temp.no == heroNode.no){
flag = true;
break;
}
temp = temp.next;
}
if(flag){
temp.name = heroNode.name;
temp.nickName = heroNode.nickName;
}else{
System.out.printf("未找到该编号%d", heroNode.no);
}
}
public void delete(int no){
if(head.next == null){
System.out.println("链表为空,无法删除");
return;
}
HeroNode temp = head.next;
boolean flag = false;
while(true){
if(temp == null){
break;
}
if(temp.no == no){
flag = true;
break;
}
temp = temp.next;
}
if(flag){
temp.pre.next = temp.next;
if(temp.next != null){
temp.next.pre = temp.pre;
}
}else{
System.out.printf("在链表中不存在编号%d", no);
}
}
}
class HeroNode{
public int no;
public String name;
public String nickName;
public HeroNode next;
public HeroNode pre;
public HeroNode(int no, String name, String nickName){
this.no = no;
this.name = name;
this.nickName = nickName;
}
@Override
public String toString() {
return "HeroNode[no=" + no + ",name=" + name + ",nickName=" + nickName + "]";
}
}
3.3环形单向链表
public class CircleLinkedList {
public static void main(String[] args) {
LinkedList_circle linkedList = new LinkedList_circle();
linkedList.add(5);
linkedList.show();
}
}
class LinkedList_circle{
private Boy first = null;
public void add(int nums){
if(nums < 1){
System.out.println("nums的值不正确");
return;
}
Boy currentBoy = null;
for (int i = 1; i <= nums; i++) {
Boy boy = new Boy(i);
if(i == 1){
first = boy;
first.setNext(first);
currentBoy = first;
}else{
currentBoy.setNext(boy);
boy.setNext(first);
currentBoy = boy;
}
}
}
public void show(){
if(first == null){
System.out.println("没有任何boy");
return;
}
Boy curBoy = first;
while(true){
System.out.printf("小孩的编号%d\n", curBoy.getNo());
if(curBoy.getNext() == first){
break;
}
curBoy = curBoy.getNext();
}
}
}
class Boy{
private int no;
private Boy next;
public Boy(int no){
this.no = no;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public void setNext(Boy next) {
this.next = next;
}
public Boy getNext() {
return next;
}
}
4.栈
import java.util.Scanner;
import javax.lang.model.element.Element;
public class ArrayStack {
public static void main(String[] args) {
String expression = "3+2*6-2";
Stack_Array numStack = new Stack_Array(10);
Stack_Array operStack = new Stack_Array(10);
int index = 0;
int num1 = 0;
int num2 = 0;
int oper = 0;
int res = 0;
char ch = ' ';
String keepNum = "";
while(true){
ch = expression.substring(index, index + 1).charAt(0);
if(operStack.isOper(ch)){
if(!operStack.isEmpty()){
if(operStack.priority(ch) <= operStack.priority(operStack.peek())){
num1 = numStack.pop();
num2 = numStack.pop();
oper = operStack.pop();
res = numStack.cal(num1, num2, oper);
numStack.push(res);
operStack.push(ch);
}
}else{
operStack.push(ch);
}
}else{
keepNum += ch;
if(index == expression.length() - 1){
numStack.push(Integer.parseInt(keepNum));
}else{
if(operStack.isOper(expression.substring(index+1, index+2).charAt(0))){
numStack.push(Integer.parseInt(keepNum));
keepNum = "";
}
}
}
index++;
if(index >= expression.length()){
break;
}
}
while(true){
if(operStack.isEmpty()){
break;
}
num1 = numStack.pop();
num2 = numStack.pop();
oper = operStack.pop();
res = numStack.cal(num1, num2, oper);
numStack.push(res);
}
System.out.printf("表达式%s = %d", expression, numStack.pop());
}
}
class Stack_Array{
private int maxSize;
private int[] stack;
private int top = -1;
public Stack_Array(int maxSize){
this.maxSize = maxSize;
stack = new int[this.maxSize];
}
public boolean isFull(){
return top == maxSize - 1;
}
public boolean isEmpty(){
return top == -1;
}
public void push(int value){
if(isFull()){
System.out.println("栈满.");
return;
}
top++;
stack[top] = value;
}
public int pop(){
if(isEmpty()){
throw new RuntimeException("栈空.");
}
int value = stack[top];
top--;
return value;
}
public void show(){
if(isEmpty()){
System.out.println("栈空.");
}
for (int i = top; i >= 0; i--) {
System.out.printf("stack[%d]=%d\n", i, stack[i]);
}
}
public int priority(int oper){
if(oper == '*' || oper == '/'){
return 1;
}else if(oper == '+' || oper == '-'){
return 0;
}else{
return -1;
}
}
public boolean isOper(char val){
return val == '+' || val == '-' || val == '*' || val == '/';
}
public int cal(int num1, int num2, int oper){
int res = 0;
switch (oper) {
case '+':
res = num1 + num2;
break;
case '-':
res = num2 - num1;
break;
case '*':
res = num1 * num2;
break;
case '/':
res = num2 / num1;
break;
default:
break;
}
return res;
}
public int peek(){
return stack[top];
}
}
5.排序算法
排序算法 | 平均时间复杂度 | 最好情况 | 最坏情况 | 空间复杂度 | 排序方式 | 稳定性 |
---|
冒泡排序 | O(n^2) | O(n) | O(n^2) | O(1) | In-place | 稳定 | 选择排序 | O(n^2) | O(n^2) | O(n^2) | O(1) | In-place | 不稳定 | 插入排序 | O(n^2) | O(n^2) | O(n^2) | O(1) | In-place | 稳定 | 希尔排序 | O(nlogn) | O(nlog2(n)) | O(nlog2(n)) | O(1) | In-place | 不稳定 | 归并排序 | O(nlogn) | O(nlogn) | O(nlogn) | O(n) | Out-place | 稳定 | 快速排序 | O(nlogn) | O(nlogn) | O(n^2) | O(logn) | In-place | 不稳定 | 堆排序 | O(nlogn) | O(nlogn) | O(nlogn) | O(1) | In-place | 不稳定 | 计数排序 | O(n + k) | O(n + k) | O(n + k) | O(k) | Out-place | 稳定 | 桶排序 | O(n + k) | O(n + k) | O(n^2) | O(n + k) | Out-place | 稳定 | 基数排序 | O(n x k) | O(n x k) | O(n x k) | O(n + k) | Out-place | 稳定 |
5.1冒泡排序
import java.util.Arrays;
public class BubbleSort {
public static void main(String[] args) {
int arr[] = {3, 9, -1, 10, -2};
System.out.println("冒泡排序前数组:" + Arrays.toString(arr));
bubbleSort(arr);
System.out.println("冒泡排序后数组:" + Arrays.toString(arr));
}
public static void bubbleSort(int [] arr){
int temp = 0;
boolean flag = false;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr.length - 1 - i; j++) {
if(arr[j] > arr[j + 1]){
flag = true;
temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
if(!flag){
break;
}else{
flag = false;
}
}
}
}
5.2选择排序
import java.util.Arrays;
public class SelectSort {
public static void main(String[] args) {
int[] arr = {101, 34, 119, 1};
System.out.println("选择排序之前:" + Arrays.toString(arr));
selectSort(arr);
System.out.println("选择排序之后:" + Arrays.toString(arr));
}
public static void selectSort(int[] arr){
int min = 0;
int index;
for (int i = 0; i < arr.length; i++) {
min = arr[i];
index = i;
for (int j = i + 1; j < arr.length; j++) {
if(min > arr[j]){
min = arr[j];
index = j;
}
}
arr[index] = arr[i];
arr[i] = min;
}
}
}
5.3插入排序
import java.util.Arrays;
public class InsertSort {
public static void main(String[] args) {
int[] arr = {17, 3, 25, 14, 20, 9};
System.out.println("插入排序前的数组:"+ Arrays.toString(arr));
insertSort(arr);
System.out.println("插入排序后的数组:"+ Arrays.toString(arr));
}
public static void insertSort(int[] arr){
for (int i = 1; i < arr.length; i++) {
int insertVal = arr[i];
int insertIndex = i - 1;
while(insertIndex >= 0 && insertVal < arr[insertIndex]){
arr[insertIndex + 1] =arr[insertIndex];
insertIndex--;
}
arr[insertIndex + 1] = insertVal;
}
}
}
5.4希尔排序
import java.util.Arrays;
public class ShellSort {
public static void main(String[] args) {
int[] arr = {8, 9, 1, 7, 2, 3, 5, 4, 6, 0};
System.out.println("排序前:"+ Arrays.toString(arr));
shellSort2(arr);
System.out.println("排序后:"+ Arrays.toString(arr));
}
public static void shellSort(int[] arr){
int temp = 0;
for (int i = arr.length / 2; i > 0; i /= 2) {
for (int j = i; j < arr.length; j++) {
for (int k = j - i; k >= 0; k -= i) {
if(arr[k] > arr[k + i]){
temp = arr[k];
arr[k] = arr[k + i];
arr[k + i] = temp;
}
}
}
}
}
public static void shellSort2(int[] arr){
for (int i = arr.length / 2; i > 0; i/=2) {
for (int k = i; k < arr.length; k++) {
int j = k;
int temp = arr[j];
while(j - i >= 0 && temp < arr[j - i]){
arr[j] = arr[j - i];
j -= i;
}
arr[j] = temp;
}
}
}
}
5.5快速排序
import java.util.Arrays;
public class QuickSort {
public static void main(String[] args) {
int[] arr = {-9, 78, 0, 23, -567, 70};
System.out.println("快速排序前数组为:" + Arrays.toString(arr));
qucikSort(arr, 0, arr.length - 1);
System.out.println("快速排序后数组为:" + Arrays.toString(arr));
}
public static void qucikSort(int[] arr, int left, int right){
int l = left;
int r = right;
int temp = 0;
int pivot = arr[(left + right) / 2];
while(l < r){
while(arr[l] < pivot){
l += 1;
}
while(arr[r] > pivot){
r -= 1;
}
if(l >= r){
break;
}
temp = arr[l];
arr[l] = arr[r];
arr[r] = temp;
if(arr[l] == pivot){
r -= 1;
}
if(arr[r] == pivot){
l += 1;
}
}
if(l == r){
l += 1;
r -= 1;
}
if(left < r){
qucikSort(arr, left, r);
}
if(right > l){
qucikSort(arr, l, right);
}
}
}
5.6归并排序
import java.util.Arrays;
public class MergeSort {
public static void main(String[] args) {
int[] arr = {8, 4, 5, 6, 1, 3, 6, 2};
int[] temp = new int[arr.length];
System.out.println("归并排序前的数组是:" + Arrays.toString(arr));
mergeSort(arr, 0, arr.length - 1, temp);
System.out.println("归并排序后的数组是:" + Arrays.toString(arr));
}
public static void mergeSort(int[] arr, int left, int right, int[] temp){
if(left < right){
int mid = (left + right) / 2;
mergeSort(arr, left, mid, temp);
mergeSort(arr, mid + 1, right, temp);
merge(arr, left, mid, right, temp);
}
}
public static void merge(int[] arr, int left, int mid, int right, int[] temp){
int i = left;
int j = mid + 1;
int t = 0;
while(i <= mid && j <= right){
if(arr[i] <= arr[j]){
temp[t] = arr[i];
i++;
t++;
}else{
temp[t] = arr[j];
j++;
t++;
}
}
while(i <= mid){
temp[t] = arr[i];
i++;
t++;
}
while(j <= right){
temp[t] = arr[j];
j++;
t++;
}
t = 0;
int tempLeft = left;
while(tempLeft <= right){
arr[tempLeft] = temp[t];
t++;
tempLeft++;
}
}
}
5.7基数排序
import java.util.Arrays;
public class RadixSort {
public static void main(String[] args) {
int[] arr = {53, 3, 542, 748, 14, 214};
radixSort(arr);
}
public static void radixSort(int[] arr){
int[][] bucket = new int[10][arr.length];
int[] bucketElementCounts = new int[10];
int max = arr[0];
for (int i = 1; i < arr.length; i++) {
if(arr[i] > max){
max = arr[i];
}
}
int maxLength = (max + "").length();
for (int i = 0; i < maxLength; i++) {
for (int j = 0; j < arr.length; j++) {
int digitOfElement = arr[j] / (int)Math.pow(10, i) % 10;
bucket[digitOfElement][bucketElementCounts[digitOfElement]] = arr[j];
bucketElementCounts[digitOfElement]++;
}
int index = 0;
for (int k = 0; k < bucketElementCounts.length; k++) {
if(bucketElementCounts[k] != 0){
for (int l = 0; l < bucketElementCounts[k]; l++) {
arr[index++] = bucket[k][l];
}
}
bucketElementCounts[k] = 0;
}
System.out.println("第" + (i + 1) + "轮:" + Arrays.toString(arr));
}
}
}
5.8堆排序
package Sort;
import java.util.Arrays;
public class HeapSort {
public static void main(String[] args) {
int[] arr = {4, 6, 8, 5, 9};
headSort(arr);
System.out.println(Arrays.toString(arr));
}
public static void headSort(int[] arr) {
int temp = 0;
System.out.println("堆排序!!!");
for (int i = arr.length / 2 - 1; i >= 0; i--) {
adjustHeap(arr, i, arr.length);
}
for (int j = arr.length - 1; j > 0; j--) {
temp = arr[j];
arr[j] = arr[0];
arr[0] = temp;
adjustHeap(arr, 0, j);
}
}
public static void adjustHeap(int[] arr, int i, int length) {
int temp = arr[i];
for (int k = i * 2 + 1; k < length; k = k * 2 + 1) {
if(k + 1 < length && arr[k] < arr[k + 1]) {
k++;
}
if(arr[k] > temp) {
arr[i] = arr[k];
i = k;
}else {
break;
}
}
arr[i] = temp;
}
}
6.查找算法
6.1二分查找
package Search;
public class BinarySearch {
public static void main(String[] args) {
int[] arr = {1, 8, 10, 89, 1000, 1234};
int index = binarySearch(arr, 0, arr.length, 1234);
System.out.println("索引为:" + index);
}
public static int binarySearch(int[] arr, int left, int right, int findVal){
if(left > right){
return -1;
}
int mid = (left + right) / 2;
int midVal = arr[mid];
if(findVal > midVal){
return binarySearch(arr, mid + 1, right, findVal);
}else if(findVal < midVal){
return binarySearch(arr, left, mid - 1, findVal);
}else{
return mid;
}
}
}
6.2插值查找
package Search;
public class InsertValueSearch {
public static void main(String[] args) {
int[] arr = new int[100];
for (int i = 0; i < 100; i++) {
arr[i] = i + 1;
}
int index = insertValueSearch(arr, 0, args.length, 30);
System.out.println("索引为:" + index);
}
public static int insertValueSearch(int[] arr, int left, int right, int findVal){
if(left > right || findVal < arr[0] || findVal > arr[arr.length - 1]){
return -1;
}
int mid = left + (right - left) * (findVal - arr[left]) / (arr[right] - arr[left]);
int midVal = arr[mid];
if(findVal > midVal){
return insertValueSearch(arr, mid + 1, right, findVal);
}else if(findVal < midVal){
return insertValueSearch(arr, left, mid - 1, findVal);
}else{
return mid;
}
}
}
7.哈希表
package HashTable;
import java.util.Scanner;
import jdk.nashorn.internal.ir.EmptyNode;
public class HashTabDemo {
public static void main(String[] args) {
HashTab hTab = new HashTab(7);
String key = "";
Scanner sc = new Scanner(System.in);
while(true){
System.out.println("add:添加雇员");
System.out.println("list:显示雇员");
System.out.println("exit:退出系统");
key = sc.next();
switch (key) {
case "add":
System.out.println("输入id");
int id = sc.nextInt();
System.out.println("输入姓名");
String name = sc.next();
Emp emp = new Emp(id, name);
hTab.add(emp);
break;
case "list":
hTab.list();
break;
case "find":
System.out.println("输入查找的id");
id = sc.nextInt();
hTab.findEmpById(id);
break;
case "exit":
sc.close();
System.exit(0);
default:
break;
}
}
}
}
class Emp {
public int id;
public String name;
public Emp next;
public Emp(int id, String name) {
this.id = id;
this.name = name;
}
}
class EmpLikedList {
private Emp head;
public void add(Emp emp){
if(head == null){
head = emp;
return;
}
Emp curEmp = head;
while(true){
if(curEmp.next == null){
break;
}
curEmp = curEmp.next;
}
curEmp.next = emp;
}
public void list(int no){
if(head == null){
System.out.println("第"+ (no + 1) +"链表信息为空.");
return;
}
System.out.println("第"+ (no + 1) +"链表的信息为:");
Emp curEmp = head;
while(true){
System.out.printf("=> id = %d, name=%s\t'", curEmp.id, curEmp.name);
if(curEmp.next == null){
break;
}
curEmp = curEmp.next;
}
System.out.println();
}
public Emp findEmpById(int id){
if(head == null){
System.out.println("链表为空");
return null;
}
Emp curEmp = head;
while(true){
if(curEmp.id == id){
break;
}
if(curEmp.next == null){
curEmp = null;
break;
}
curEmp = curEmp.next;
}
return curEmp;
}
}
class HashTab{
private EmpLikedList[] empLikedLists;
private int size;
public HashTab(int size) {
this.size = size;
empLikedLists = new EmpLikedList[size];
for (int i = 0; i < size; i++) {
empLikedLists[i] = new EmpLikedList();
}
}
public void add(Emp emp){
int empLikedListNo = hashFun(emp.id);
empLikedLists[empLikedListNo].add(emp);
}
public int hashFun(int id){
return id % size;
}
public void list(){
for (int i = 0; i < size; i++) {
empLikedLists[i].list(i);
}
}
public void findEmpById(int id){
int empLikedListNo = hashFun(id);
Emp emp = empLikedLists[empLikedListNo].findEmpById(id);
if(emp != null){
System.out.printf("在第%d找到雇员id = %d\n", (empLikedListNo + 1), id);
}else{
System.out.println("没有找到该雇员信息.");
}
}
}
8.二叉树
8.1 二叉树链表实现
package Tree;
public class BinaryTree {
public static void main(String[] args) {
Tree tree = new Tree();
HeroNode node1 = new HeroNode(1, "zhangsan");
HeroNode node2 = new HeroNode(2, "lis");
HeroNode node3 = new HeroNode(3, "wanger");
HeroNode node4 = new HeroNode(4, "mazi");
node1.setLeft(node2);
node1.setRight(node3);
node3.setRight(node4);
tree.setRoot(node1);
tree.preOrder();
tree.infixOrder();
tree.postOrder();
}
}
class Tree {
private HeroNode root;
public void setRoot(HeroNode root) {
this.root = root;
}
public void preOrder() {
if(this.root != null){
this.root.preOrder();
}else{
System.out.println("二叉树为空.");
}
}
public void infixOrder() {
if(this.root != null){
this.root.infixOrder();
}else{
System.out.println("二叉树为空.");
}
}
public void postOrder() {
if(this.root != null){
this.root.postOrder();
}else{
System.out.println("二叉树为空.");
}
}
public HeroNode preOrderSearch(int no){
if(root != null){
return root.preOrderSearch(no);
}else{
return null;
}
}
public HeroNode infixOrderSearch(int no){
if(root != null){
return root.infixOrderSearch(no);
}else{
return null;
}
}
public HeroNode postOrderSearch(int no){
if(root != null){
return root.postOrderSearch(no);
}else{
return null;
}
}
public void delNode(int no){
if(root != null){
if(root.getNo() == no){
root = null;
}else{
root.delNode(no);
}
}else{
System.out.println("空树,不能删除.");
}
}
}
class HeroNode {
private int no;
private String name;
private HeroNode left;
private HeroNode right;
public HeroNode(int no, String name) {
this.no = no;
this.name = name;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public HeroNode getLeft() {
return left;
}
public void setLeft(HeroNode left) {
this.left = left;
}
public HeroNode getRight() {
return right;
}
public void setRight(HeroNode right) {
this.right = right;
}
@Override
public String toString() {
return "HeroNode [no=" + no + ", name=" + name + "]";
}
public void preOrder() {
System.out.println(this);
if(this.left != null){
this.left.preOrder();
}
if(this.right != null){
this.right.preOrder();
}
}
public void infixOrder() {
if(this.left != null){
this.left.infixOrder();
}
System.out.println(this);
if(this.right != null){
this.right.infixOrder();
}
}
public void postOrder() {
if(this.left != null){
this.left.postOrder();
}
if(this.right != null){
this.right.postOrder();
}
System.out.println(this);
}
public HeroNode preOrderSearch(int no){
if(this.no == no){
return this;
}
HeroNode node = null;
if(this.left != null){
node = this.left.preOrderSearch(no);
}
if(node != null){
return node;
}
if(this.right != null){
node = this.right.preOrderSearch(no);
}
return node;
}
public HeroNode infixOrderSearch(int no){
HeroNode node = null;
if(this.left != null){
node = this.left.infixOrderSearch(no);
}
if(node != null){
return node;
}
if(this.no == no){
return this;
}
if(this.right != null){
node = this.right.infixOrderSearch(no);
}
return node;
}
public HeroNode postOrderSearch(int no){
HeroNode node = null;
if(this.left != null){
node = this.left.postOrderSearch(no);
}
if(node != null){
return node;
}
if(this.right != null){
node = this.right.postOrderSearch(no);
}
if(this.no == no){
return this;
}
return node;
}
public void delNode(int no){
if(this.left != null && this.left.no == no){
this.left = null;
return;
}
if(this.right != null && this.right.no == no){
this.right = null;
return;
}
if(this.left != null){
this.left.delNode(no);
}
if(this.right != null){
this.right.delNode(no);
}
}
}
8.2顺序存储二叉树
package Tree;
public class ArrBinaryTree {
public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5, 6, 7};
arrTree tree = new arrTree(arr);
tree.preOrder();
}
}
class arrTree{
private int[] arr;
public arrTree(int[] arr) {
this.arr = arr;
}
public void preOrder() {
this.preOrder(0);
}
public void preOrder(int index){
if(arr == null || arr.length == 0){
System.err.println("数组为空,不能遍历.");
}
System.out.println(arr[index]);
if((index * 2 + 1) < arr.length){
preOrder(2 * index + 1);
}
if((index * 2 + 2) < arr.length){
preOrder(2 * index + 2);
}
}
}
8.3线索化二叉树
package Tree;
public class ThreadBinaryTree {
public static void main(String[] args) {
ThreadHeroNode root = new ThreadHeroNode(1, "tom");
ThreadHeroNode node2 = new ThreadHeroNode(3, "jack");
ThreadHeroNode node3 = new ThreadHeroNode(6, "smith");
ThreadHeroNode node4 = new ThreadHeroNode(8, "mary");
ThreadHeroNode node5 = new ThreadHeroNode(10, "king");
ThreadHeroNode node6 = new ThreadHeroNode(14, "dim");
root.setLeft(node2);
root.setRight(node3);
node2.setLeft(node4);
node2.setRight(node5);
node3.setLeft(node6);
ThreadTree tree = new ThreadTree();
tree.setRoot(root);
tree.threadNodes();
ThreadHeroNode leftNode = node5.getLeft();
System.out.println("10号的前驱节点是:" + leftNode);
ThreadHeroNode rightNode = node5.getRight();
System.out.println("10号的后继节点是:" + rightNode);
System.out.println("使用线索化的方式遍历线索化二叉树");
tree.threadList();
}
}
class ThreadTree {
private ThreadHeroNode root;
private ThreadHeroNode pre = null;
public void setRoot(ThreadHeroNode root) {
this.root = root;
}
public void threadNodes(){
this.threadNodes(root);
}
public void threadNodes(ThreadHeroNode node){
if(node == null){
return;
}
threadNodes(node.getLeft());
if(node.getLeft() == null){
node.setLeft(pre);
node.setLeftType(1);
}
if(pre != null && pre.getRight() == null){
pre.setRight(node);
pre.setRightType(1);
}
threadNodes(node.getRight());
}
public void threadList(){
ThreadHeroNode node = root;
while(node != null){
while(node.getLeftType() == 0){
node = node.getLeft();
}
System.out.println(node);
while(node.getRightType() == 1){
node = node.getRight();
System.out.println(node);
}
node = node.getRight();
}
}
}
class ThreadHeroNode {
private int no;
private String name;
private ThreadHeroNode left;
private ThreadHeroNode right;
private int leftType;
private int rightType;
public int getLeftType() {
return leftType;
}
public void setLeftType(int leftType) {
this.leftType = leftType;
}
public int getRightType() {
return rightType;
}
public void setRightType(int rightType) {
this.rightType = rightType;
}
public ThreadHeroNode(int no, String name) {
this.no = no;
this.name = name;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public ThreadHeroNode getLeft() {
return left;
}
public void setLeft(ThreadHeroNode left) {
this.left = left;
}
public ThreadHeroNode getRight() {
return right;
}
public void setRight(ThreadHeroNode right) {
this.right = right;
}
@Override
public String toString() {
return "HeroNode [no=" + no + ", name=" + name + "]";
}
}
8.4二叉排序树
package Tree;
public class BinarySortTree {
public static void main(String[] args) {
int[] arr = {7, 3, 10, 12, 5, 1, 9};
BST bst = new BST();
for (int i = 0; i < arr.length; i++) {
bst.add(new BstNode(arr[i]));
}
System.out.println("中序遍历二叉树");
bst.infixOrder();
}
}
class BST {
private BstNode root;
public BstNode search(int value) {
if(root == null) {
return null;
}else {
return root.search(value);
}
}
public BstNode searchParent(int value) {
if(root == null) {
return null;
}else {
return root.searchParent(value);
}
}
public int delRightTreeMin(BstNode node) {
BstNode target = node;
while(target.left != null) {
target = target.left;
}
delNode(target.value);
return target.value;
}
public void delNode(int value) {
if(root == null){
return;
}else {
BstNode targetNode = search(value);
if(targetNode == null) {
return;
}
if(root.left == null && root.right == null) {
root = null;
return;
}
BstNode parent = searchParent(value);
if(targetNode.left == null && targetNode.right == null) {
if(parent.left != null && parent.left.value == value) {
parent.left = null;
}else if(parent.right != null && parent.right.value == value) {
parent.right = null;
}
}else if(targetNode.left != null && targetNode.right != null) {
int minVal = delRightTreeMin(targetNode.right);
targetNode.value = minVal;
}else {
if(targetNode.left != null) {
if(parent!=null){
if(parent.left.value == value) {
parent.left = targetNode.left;
}else {
parent.right = targetNode.left;
}
}else {
root = targetNode.left;
}
}else {
if(parent != null){
if(parent.left.value == value) {
parent.left = targetNode.right;
}else {
parent.right = targetNode.right;
}
}else {
root = targetNode.right;
}
}
}
}
}
public void add(BstNode node) {
if(root == null) {
root = node;
}else {
root.add(node);
}
}
public void infixOrder() {
if(root != null) {
root.infixOrder();
}else {
System.out.println("二叉排序树为空,不能遍历.");
}
}
}
class BstNode {
int value;
BstNode left;
BstNode right;
public BstNode(int value) {
this.value = value;
}
@Override
public String toString() {
return "BstNode [value=" + value + "]";
}
public void add(BstNode node) {
if(node == null) {
return;
}
if(node.value < this.value) {
if(this.left == null) {
this.left = node;
}else {
this.left.add(node);
}
}else {
if(this.right == null) {
this.right = node;
}else {
this.right.add(node);
}
}
}
public void infixOrder() {
if(this.left != null) {
this.left.infixOrder();
}
System.out.println(this);
if(this.right != null) {
this.right.infixOrder();
}
}
public BstNode search(int value) {
if(value == this.value) {
return this;
}else if(value < this.value) {
if(this.left == null) {
return null;
}
return this.left.search(value);
}else{
if(this.right == null) {
return null;
}
return this.right.search(value);
}
}
public BstNode searchParent(int value) {
if((this.left != null && this.left.value == value) || (this.right != null && this.right.value == value)) {
return this;
}else{
if(value < this.value && this.left != null) {
return this.left.searchParent(value);
}else if(value >= this.value && this.right != null) {
return this.right.searchParent(value);
}else{
return null;
}
}
}
}
8.5平衡二叉树
package Tree;
public class AVLTree {
public static void main(String[] args) {
int[] arr = {4, 3, 6, 5, 7, 8};
AVL avl = new AVL();
for (int i = 0; i < arr.length; i++) {
avl.add(new AvlNode(arr[i]));
}
System.out.println("中序遍历");
avl.infixOrder();
System.out.println("没有做平衡处理前树的高度:" + avl.getRoot().height());
System.out.println("树的左子树的高度为:" + avl.getRoot().leftHeight());
System.out.println("树的右子树的高度为:" + avl.getRoot().rightHeight());
}
}
class AVL {
private AvlNode root;
public AvlNode getRoot() {
return root;
}
public AvlNode search(int value) {
if(root == null) {
return null;
}else {
return root.search(value);
}
}
public AvlNode searchParent(int value) {
if(root == null) {
return null;
}else {
return root.searchParent(value);
}
}
public int delRightTreeMin(AvlNode node) {
AvlNode target = node;
while(target.left != null) {
target = target.left;
}
delNode(target.value);
return target.value;
}
public void delNode(int value) {
if(root == null){
return;
}else {
AvlNode targetNode = search(value);
if(targetNode == null) {
return;
}
if(root.left == null && root.right == null) {
root = null;
return;
}
AvlNode parent = searchParent(value);
if(targetNode.left == null && targetNode.right == null) {
if(parent.left != null && parent.left.value == value) {
parent.left = null;
}else if(parent.right != null && parent.right.value == value) {
parent.right = null;
}
}else if(targetNode.left != null && targetNode.right != null) {
int minVal = delRightTreeMin(targetNode.right);
targetNode.value = minVal;
}else {
if(targetNode.left != null) {
if(parent!=null){
if(parent.left.value == value) {
parent.left = targetNode.left;
}else {
parent.right = targetNode.left;
}
}else {
root = targetNode.left;
}
}else {
if(parent != null){
if(parent.left.value == value) {
parent.left = targetNode.right;
}else {
parent.right = targetNode.right;
}
}else {
root = targetNode.right;
}
}
}
}
}
public void add(AvlNode node) {
if(root == null) {
root = node;
}else {
root.add(node);
}
}
public void infixOrder() {
if(root != null) {
root.infixOrder();
}else {
System.out.println("二叉排序树为空,不能遍历.");
}
}
}
class AvlNode {
int value;
AvlNode left;
AvlNode right;
public AvlNode(int value) {
this.value = value;
}
@Override
public String toString() {
return "AvlNode [value=" + value + "]";
}
private void leftRotate() {
AvlNode newNode = new AvlNode(value);
newNode.left = left;
newNode.right = right.left;
value = right.value;
right = right.right;
left = newNode;
}
private void rightRotate() {
AvlNode newNode = new AvlNode(value);
newNode.right = right;
newNode.left = left.right;
newNode.left = left.right;
value = left.value;
left = left.left;
}
public int leftHeight() {
if(left == null) {
return 0;
}
return left.height();
}
public int rightHeight() {
if(right == null) {
return 0;
}
return right.height();
}
public int height() {
return Math.max(left == null ? 0 : left.height(), right == null ? 0 : right.height()) + 1;
}
public void add(AvlNode node) {
if(node == null) {
return;
}
if(node.value < this.value) {
if(this.left == null) {
this.left = node;
}else {
this.left.add(node);
}
}else {
if(this.right == null) {
this.right = node;
}else {
this.right.add(node);
}
}
if(rightHeight() - leftHeight() > 1) {
if(right != null && right.leftHeight() > right.rightHeight()) {
right.rightRotate();
leftRotate();
}else {
leftRotate();
}
}
if(leftHeight() - rightHeight() > 1) {
if(left != null && left.rightHeight() > left.leftHeight()) {
left.leftRotate();
rightRotate();
}else {
rightRotate();
}
}
}
public void infixOrder() {
if(this.left != null) {
this.left.infixOrder();
}
System.out.println(this);
if(this.right != null) {
this.right.infixOrder();
}
}
public AvlNode search(int value) {
if(value == this.value) {
return this;
}else if(value < this.value) {
if(this.left == null) {
return null;
}
return this.left.search(value);
}else{
if(this.right == null) {
return null;
}
return this.right.search(value);
}
}
public AvlNode searchParent(int value) {
if((this.left != null && this.left.value == value) || (this.right != null && this.right.value == value)) {
return this;
}else{
if(value < this.value && this.left != null) {
return this.left.searchParent(value);
}else if(value >= this.value && this.right != null) {
return this.right.searchParent(value);
}else{
return null;
}
}
}
}
9.哈夫曼树
9.1哈夫曼树构造
package Tree;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class HuffmanTree {
public static void main(String[] args) {
int[] arr = {13, 7, 8, 3, 29, 6, 1};
Node root = createHuffmanTree(arr);
preOrder(root);
}
public static void preOrder(Node root) {
if(root != null) {
root.preOrder();
}else {
System.out.println("空树,不能遍历.");
}
}
public static Node createHuffmanTree(int[] arr){
List<Node> nodes = new ArrayList<>();
for (int value : arr) {
nodes.add(new Node(value));
}
while(nodes.size() > 1){
Collections.sort(nodes);
Node leftNode = nodes.get(0);
Node rightNode = nodes.get(1);
Node parent = new Node(leftNode.value + rightNode.value);
parent.left = leftNode;
parent.right = rightNode;
nodes.remove(leftNode);
nodes.remove(rightNode);
nodes.add(parent);
}
return nodes.get(0);
}
}
class Node implements Comparable<Node> {
int value;
Node left;
Node right;
public Node(int value){
this.value = value;
}
public void preOrder() {
System.out.println(this);
if(this.left != null) {
this.left.preOrder();
}
if(this.right != null) {
this.right.preOrder();
}
}
@Override
public int compareTo(Node o) {
return this.value - o.value;
}
@Override
public String toString() {
return "Node [value=" + value + "]";
}
}
9.2哈夫曼树压缩和解压缩
package Tree;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class HuffmanCode {
public static void main(String[] args) {
String content = "i like like like java do you like a java";
byte[] contentBytes = content.getBytes();
byte[] huffmanCodeBytes = huffmanZip(contentBytes);
System.out.println("压缩后的结果是:" + Arrays.toString(huffmanCodeBytes));
byte[] sourceBytes = decode(huffmanCodes, huffmanCodeBytes);
System.out.println("解压缩后的结果是:" + new String(sourceBytes));
}
static Map<Byte, String> huffmanCodes = new HashMap<>();
static StringBuilder stringBuilder = new StringBuilder();
private static byte[] decode(Map<Byte, String> huffmanCodes, byte[] huffmanBytes) {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < huffmanBytes.length; i++) {
boolean flag = (i == huffmanBytes.length - 1);
stringBuilder.append(byteToBitString(!flag, huffmanBytes[i]));
}
Map<String, Byte> map = new HashMap<>();
for(Map.Entry<Byte, String> entry : huffmanCodes.entrySet()) {
map.put(entry.getValue(), entry.getKey());
}
List<Byte> list = new ArrayList<>();
for (int i = 0; i < stringBuilder.length();) {
int count = 1;
boolean flag = true;
Byte b = null;
while(flag) {
String key = stringBuilder.substring(i, i + count);
b = map.get(key);
if(b == null) {
count++;
}else {
flag = false;
}
}
list.add(b);
i += count;
}
byte[] b = new byte[list.size()];
for (int i = 0; i < b.length; i++) {
b[i] = list.get(i);
}
return b;
}
private static String byteToBitString(boolean flag, byte b){
int temp = b;
if(flag) {
temp |= 256;
}
String str = Integer.toBinaryString(temp);
if(flag) {
return str.substring(str.length() - 8);
}else {
return str;
}
}
private static byte[] huffmanZip(byte[] bytes) {
List<Node_Code> nodes = getNodes(bytes);
Node_Code huffmanTreeRoot = createHuffmanTree(nodes);
Map<Byte, String> huffmanCodes = getCodes(huffmanTreeRoot);
byte[] huffmanCodeBytes = zip(bytes, huffmanCodes);
return huffmanCodeBytes;
}
private static byte[] zip(byte[] bytes, Map<Byte, String> huffmanCodes) {
StringBuilder stringBuilder = new StringBuilder();
for (byte b : bytes) {
stringBuilder.append(huffmanCodes.get(b));
}
int len = (stringBuilder.length() + 7) / 8;
byte[] by = new byte[len];
int index = 0;
for (int i = 0; i < stringBuilder.length(); i+=8) {
String strByte;
if(i + 8 > stringBuilder.length()){
strByte = stringBuilder.substring(i);
}else {
strByte = stringBuilder.substring(i, i + 8);
}
by[index] = (byte)Integer.parseInt(strByte, 2);
index++;
}
return by;
}
private static void getCodes(Node_Code node, String code, StringBuilder stringBuilder) {
StringBuilder stringBuilder2 = new StringBuilder(stringBuilder);
stringBuilder2.append(code);
if(node != null) {
if(node.data == null) {
getCodes(node.left, "0", stringBuilder2);
getCodes(node.right, "1", stringBuilder2);
}else {
huffmanCodes.put(node.data, stringBuilder2.toString());
}
}
}
private static Map<Byte, String> getCodes(Node_Code root) {
if(root == null) {
return null;
}
getCodes(root.left, "0", stringBuilder);
getCodes(root.right, "1", stringBuilder);
return huffmanCodes;
}
private static void preOrder(Node_Code root) {
if(root != null) {
root.preOrder();
}else {
System.out.println("树空.");
}
}
private static List<Node_Code> getNodes(byte[] bytes){
ArrayList<Node_Code> nodes = new ArrayList<Node_Code>();
Map<Byte, Integer> counts = new HashMap<>();
for (byte b : bytes) {
Integer count = counts.get(b);
if(count == null) {
counts.put(b, 1);
}else {
counts.put(b, count + 1);
}
}
for(Map.Entry<Byte, Integer> entry : counts.entrySet()) {
nodes.add(new Node_Code(entry.getKey(), entry.getValue()));
}
return nodes;
}
private static Node_Code createHuffmanTree(List<Node_Code> nodes) {
while(nodes.size() > 1) {
Collections.sort(nodes);
Node_Code leftNode = nodes.get(0);
Node_Code rightNode = nodes.get(1);
Node_Code parent = new Node_Code(null, leftNode.weight + rightNode.weight);
parent.left = leftNode;
parent.right = rightNode;
nodes.remove(leftNode);
nodes.remove(rightNode);
nodes.add(parent);
}
return nodes.get(0);
}
}
class Node_Code implements Comparable<Node_Code> {
Byte data;
int weight;
Node_Code left;
Node_Code right;
public Node_Code(Byte data, int weight) {
this.data = data;
this.weight = weight;
}
@Override
public int compareTo(Node_Code o) {
return this.weight - o.weight;
}
@Override
public String toString() {
return "Node [data=" + data + ", weight=" + weight + "]";
}
public void preOrder() {
System.out.println(this);
if(this.left != null) {
this.left.preOrder();
}
if(this.right != null) {
this.right.preOrder();
}
}
}
10.图
package Graph;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
public class Graph {
private ArrayList<String> vertexList;
private int[][] edges;
private int numOfEdges;
private boolean[] isVisited = new boolean[5];
public static void main(String[] args) {
int n = 5;
String[] VertexValue = {"A", "B", "C", "D", "E"};
Graph graph = new Graph(n);
for (String value : VertexValue) {
graph.insertVertex(value);
}
graph.insertEdge(0, 1, 1);
graph.insertEdge(0, 2, 1);
graph.insertEdge(1, 2, 1);
graph.insertEdge(1, 3, 1);
graph.insertEdge(1, 4, 1);
graph.showGraph();
System.out.println("深度遍历:");
graph.dfs();
System.out.println("广度遍历:");
graph.bfs();
}
public Graph(int n) {
edges = new int[n][n];
vertexList = new ArrayList<String>();
numOfEdges = 0;
}
public void insertVertex(String vertex) {
vertexList.add(vertex);
}
public void insertEdge(int v1, int v2, int weight) {
edges[v1][v2] = weight;
edges[v2][v1] = weight;
numOfEdges++;
}
public int getNumOfVertex() {
return vertexList.size();
}
public int getNumOfEdges() {
return numOfEdges;
}
public String getValueByIndex(int i) {
return vertexList.get(i);
}
public int getWeight(int v1, int v2) {
return edges[v1][v2];
}
public void showGraph() {
for (int[] link : edges) {
System.out.println(Arrays.toString(link));
}
}
public int getFirstNeighbor(int index) {
for (int i = 0; i < vertexList.size(); i++) {
if(edges[index][i] > 0) {
return i;
}
}
return -1;
}
public int getNextNeighbor(int v1, int v2) {
for (int i = v2 + 1; i < vertexList.size(); i++) {
if(edges[v1][i] > 0) {
return i;
}
}
return -1;
}
public void dfs(boolean[] isVisited, int i) {
System.out.print(getValueByIndex(i) + "->");
isVisited[i] = true;
int w = getFirstNeighbor(i);
while(w != -1) {
if(!isVisited[w]) {
dfs(isVisited, w);
}
w = getNextNeighbor(i, w);
}
}
private void dfs() {
for (int i = 0; i < getNumOfVertex(); i++) {
if(!isVisited[i]) {
dfs(isVisited, i);
}
}
}
private void bfs(boolean[] isVisited, int i) {
int u;
int w;
LinkedList queue = new LinkedList<>();
System.out.println(getValueByIndex(i) + "->");
isVisited[i] = true;
queue.addLast(i);
while(!queue.isEmpty()) {
u = (Integer)queue.removeFirst();
w = getFirstNeighbor(u);
while(w != -1) {
if(!isVisited[w]) {
System.out.println(getValueByIndex(i) + "->");
isVisited[w] = true;
queue.add(w);
}
w = getNextNeighbor(u, w);
}
}
}
private void bfs() {
for (int i = 0; i < getNumOfVertex(); i++) {
if(!isVisited[i]) {
bfs(isVisited, i);
}
}
}
}
11.动态规划
package Dynamic;
public class KnaspackProblem {
public static void main(String[] args) {
int[] w = {1, 4, 3};
int[] val = {1500, 3000, 2000};
int m = 4;
int n = val.length;
int[][] path = new int[n+1][m+1];
int[][] v = new int[n + 1][m + 1];
for (int i = 0; i < v.length; i++) {
v[i][0] = 0;
}
for (int i = 0; i < v[0].length; i++) {
v[0][i] = 0;
}
for (int i = 1; i < v.length; i++) {
for (int j = 1; j < v[0].length; j++) {
if(w[i-1] > j) {
v[i][j] = v[i-1][j];
}else {
if(v[i-1][j] < val[i-1]+v[i-1][j-w[i-1]]) {
v[i][j] = val[i-1]+v[i-1][j-w[i-1]];
path[i][j] = 1;
}else {
v[i][j] = v[i-1][j];
}
}
}
}
for (int i = 0; i < v.length; i++) {
for (int j = 0; j < v[i].length; j++) {
System.out.println(v[i][j] + " ");
}
System.out.println();
}
int i = path.length - 1;
int j = path[0].length - 1;
while(i > 0 && j > 0) {
if(path[i][j] == 1) {
System.out.printf("第%d个物品放入背包\n", i);
j -= w[i-1];
}
i--;
}
}
}
12.最小生成树算法
12.1Prim算法
package Algorithm;
import java.util.Arrays;
public class PrimAlgorithm {
public static void main(String[] args) {
char[] data = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G'};
int verxs = data.length;
int[][] weight = new int[][] {
{10000, 5, 7, 10000, 10000, 10000, 2},
{5, 10000, 10000, 9, 10000, 10000, 3},
{7, 10000, 10000, 10000, 8, 10000, 10000},
{10000, 9, 10000, 10000, 10000, 4, 10000},
{10000, 10000, 8, 10000, 10000, 5, 4},
{10000, 10000, 10000, 4, 5, 10000, 6},
{2, 3, 10000, 10000, 4, 6, 10000}
};
MGraph mGraph = new MGraph(verxs);
MinTree minTree = new MinTree();
minTree.createGraph(mGraph, verxs, data, weight);
minTree.showGraph(mGraph);
}
}
class MinTree {
public void createGraph(MGraph graph, int verxs, char[] data, int[][] weight) {
int i, j;
for (i = 0; i < verxs; i++) {
graph.data[i] = data[i];
for ( j = 0; j < verxs; j++) {
graph.weight[i][j] = weight[i][j];
}
}
}
public void showGraph(MGraph graph) {
for (int[] link : graph.weight) {
System.out.println(Arrays.toString(link));
}
}
public void prim(MGraph graph, int v) {
int visited[] = new int[graph.verxs];
for (int i = 0; i < visited.length; i++) {
visited[i] = 0;
}
visited[v] = 1;
int h1 = -1;
int h2 = -1;
int minWeight = 10000;
for (int k = 1; k < graph.verxs; k++) {
for (int i = 0; i < graph.verxs; i++) {
for (int j = 0; j < graph.verxs; j++) {
if(visited[i] == 1 && visited[j] == 0 && graph.weight[i][j] < minWeight){
minWeight = graph.weight[i][j];
h1 = i;
h2 = j;
}
}
}
System.out.println("边<" + graph.data[h1] + "," + graph.data[h2] + ">权值:" + minWeight);
visited[h2] = 1;
minWeight = 10000;
}
}
}
class MGraph {
int verxs;
char[] data;
int[][] weight;
public MGraph(int verxs) {
this.verxs = verxs;
data = new char[verxs];
weight = new int[verxs][verxs];
}
}
12.2Kruskal算法
package Algorithm;
import java.util.Arrays;
public class KruskalAlgorithm {
private int edgeNum;
private char[] vertexs;
private int[][] matrix;
private static final int INF = Integer.MAX_VALUE;
public static void main(String[] args) {
char[] data = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G'};
int[][] matrix = new int[][] {
{0, 12, INF, INF, INF, 16, 14},
{12, 0, 10, INF, INF, 7, INF},
{INF, 10, 0, 3, 5, 6, INF},
{INF, INF, 3, 0, 4, INF, INF},
{INF, INF, 5, 4, 0, 2, 8},
{16, 7, 6, INF, 2, 0, 9},
{14, INF, INF, INF, 8, 9, 0}
};
KruskalAlgorithm kruskalAlgorithm = new KruskalAlgorithm(data, matrix);
kruskalAlgorithm.print();
}
public KruskalAlgorithm(char[] vertexs, int[][] matrix){
int vlen = vertexs.length;
this.vertexs = new char[vlen];
for (int i = 0; i < vertexs.length; i++) {
this.vertexs[i] = vertexs[i];
}
this.vertexs = vertexs;
this.matrix = new int[vlen][vlen];
for (int i = 0; i < vlen; i++) {
for (int j = 0; j < vlen; j++) {
this.matrix[i][j] = matrix[i][j];
}
}
for (int i = 0; i < vlen; i++) {
for (int j = 0; j < vlen; j++) {
if(this.matrix[i][j] != INF) {
edgeNum++;
}
}
}
}
public void print() {
System.out.println("邻接矩阵为:\n");
for (int i = 0; i < vertexs.length; i++) {
for (int j = 0; j < vertexs.length; j++) {
System.out.printf("%12d\t", matrix[i][j]);
}
System.out.println();
}
}
private void sortEdge(EData[] edges) {
for (int i = 0; i < edges.length - 1; i++) {
for (int j = 0; j < edges.length - 1 - i; j++) {
if(edges[j].weight > edges[j+1].weight) {
EData temp = edges[j];
edges[j] = edges[j+1];
edges[j+1] = temp;
}
}
}
}
private int getPosition(char ch) {
for (int i = 0; i < vertexs.length; i++) {
if(vertexs[i] == ch) {
return i;
}
}
return -1;
}
private EData[] getEdges() {
int index = 0;
EData[] edges = new EData[edgeNum];
for (int i = 0; i < vertexs.length; i++) {
for (int j = i + 1; j < vertexs.length; j++) {
if(matrix[i][j] != INF) {
edges[index++] = new EData(vertexs[i], vertexs[j], matrix[i][j]);
}
}
}
return edges;
}
private int getEnd(int[] ends, int i) {
while(ends[i] != 0) {
i = ends[i];
}
return i;
}
public void kruskal() {
int index = 0;
int[] ends = new int[edgeNum];
EData[] rets = new EData[edgeNum];
EData[] edges = getEdges();
sortEdge(edges);
for (int i = 0; i < edgeNum; i++) {
int p1 = getPosition(edges[i].start);
int p2 = getPosition(edges[i].end);
int m = getEnd(ends, p1);
int n = getEnd(ends, p2);
if(m != n) {
ends[m] = n;
rets[index++] = edges[i];
}
}
System.out.println("最小生成树为:");
for (int i = 0; i < index; i++) {
System.out.println(rets[i]);
}
}
}
class EData{
char start;
char end;
int weight;
public EData(char start, char end, int weight) {
this.start = start;
this.end = end;
this.weight = weight;
}
@Override
public String toString() {
return "EData [start=" + start + ", end=" + end + ", weight=" + weight + "]";
}
}
13.最短路径
13.1迪杰斯特拉算法
package Algorithm;
import java.util.Arrays;
public class DijkstraAlgorithm {
public static void main(String[] args) {
char[] vertex = new char[]{'A', 'B', 'C', 'D', 'E', 'F', 'G'};
int[][] matrix = new int[vertex.length][vertex.length];
final int N = 65535;
matrix[0] = new int[]{N, 5, 7, N, N, N, 2};
matrix[1] = new int[]{5, N, N, 9, N, N, 3};
matrix[2] = new int[]{7, N, N, N, 8, N, N};
matrix[3] = new int[]{N, 9, N, N, N, 4, N};
matrix[4] = new int[]{N, N, 8, N, N, 5, 4};
matrix[5] = new int[]{N, N, N, 4, 5, N, 6};
matrix[6] = new int[]{2, 3, N, N, 4, 6, N};
Graph graph = new Graph(vertex, matrix);
graph.showGraph();
graph.dsj(6);
graph.showDijkstra();
}
}
class Graph{
private char[] vertex;
private int[][] matrix;
private VisitedVertex vv;
public Graph(char[] vertex, int[][] matrix) {
this.vertex = vertex;
this.matrix = matrix;
}
public void showGraph() {
for (int[] link : matrix) {
System.out.println(Arrays.toString(link));
}
}
public void dsj(int index) {
vv = new VisitedVertex(vertex.length, index);
update(index);
for (int i = 1; i < vertex.length; i++) {
index = vv.updateArr();
update(index);
}
}
private void update(int index) {
int len = 0;
for (int i = 0; i < matrix[index].length; i++) {
len = vv.getDis(index) + matrix[index][i];
if(!vv.in(i) && len < vv.getDis(i)) {
vv.updatePre(i, index);
vv.updateDis(i, len);
}
}
}
public void showDijkstra() {
vv.show();
}
}
class VisitedVertex {
public int[] already_arr;
public int[] pre_visited;
public int[] dis;
public VisitedVertex(int length, int index) {
this.already_arr = new int[length];
this.pre_visited = new int[length];
this.dis = new int[length];
Arrays.fill(dis, 65535);
this.dis[index] = 0;
}
public boolean in(int index) {
return already_arr[index] == 1;
}
public void updateDis(int index, int len) {
dis[index] = len;
}
public void updatePre(int pre, int index) {
pre_visited[pre] = index;
}
public int getDis(int index) {
return dis[index];
}
public int updateArr() {
int min = 65535, index = 0;
for (int i = 0; i < already_arr.length; i++) {
if(already_arr[i] == 0 && dis[i] < min) {
min = dis[i];
index = i;
}
}
already_arr[index] = 1;
return index;
}
public void show() {
System.out.println("======================");
for (int i : already_arr) {
System.out.print(i + " ");
}
System.out.println();
for (int i : pre_visited) {
System.out.println(i + " ");
}
System.out.println();
for (int i : dis) {
System.out.println(i + " ");
}
}
}
13.2弗洛伊德算法
package Algorithm;
import java.util.Arrays;
public class FloydAlgorithm {
public static void main(String[] args) {
char[] vertex = {'A', 'B', 'C', 'D', 'E', 'F', 'G'};
int[][] matrix = new int[vertex.length][vertex.length];
final int N = 65535;
matrix[0] = new int[]{0, 5, 7, N, N, N, 2};
matrix[1] = new int[]{5, 0, N, 9, N, N, 3};
matrix[2] = new int[]{7, N, 0, N, 8, N, N};
matrix[3] = new int[]{N, 9, N, 0, N, 4, N};
matrix[4] = new int[]{N, N, 8, N, 0, 5, 4};
matrix[5] = new int[]{N, N, N, 4, 5, 0, 6};
matrix[6] = new int[]{2, 3, N, N, 4, 6, 0};
FloydGraph graph = new FloydGraph(vertex.length, matrix, vertex);
graph.show();
}
}
class FloydGraph{
private char[] vertex;
private int[][] dis;
private int[][] pre;
public FloydGraph(int length, int[][] matrix, char[] vertex) {
this.vertex = vertex;
this.dis = matrix;
this.pre = new int[length][length];
for (int i = 0; i < length; i++) {
Arrays.fill(pre[i], i);
}
}
public void show() {
for (int i = 0; i < dis.length; i++) {
for (int j = 0; j < dis.length; j++) {
System.out.println(vertex[pre[i][j]] + " ");
}
for (int j = 0; j < dis.length; j++) {
System.out.println("("+ vertex[i] + "到"+ vertex[j] + "的最短路径是" + dis[i][j] + ")");
}
}
}
public void floyd() {
int len = 0;
for (int k = 0; k < dis.length; k++) {
for (int i = 0; i < dis.length; i++) {
for (int j = 0; j < dis.length; j++) {
len = dis[i][k] + dis[k][j];
if(len < dis[i][j]) {
dis[i][j] = len;
pre[i][j] = pre[k][j];
}
}
}
}
}
}
|