Java编程实战:手写算法与数据结构训练指南

引言
在编程的世界里,Java无疑是最受欢迎的语言之一,广泛应用于企业级开发、大数据处理、移动应用等领域。然而,无论你是初入编程殿堂的新手,还是经验丰富的老手,掌握数据结构与算法都是提升编程能力的关键。本文将带你深入探索Java中的各种基本算法和数据结构,通过详细的解释、有趣的例子和可运行的Java代码片段,助你轻松掌握这些核心技能。
一、排序算法
1. 冒泡排序
原理
:冒泡排序是一种简单的排序算法,通过重复遍历要排序的数列,比较每对相邻元素的大小,若顺序错误则交换它们的位置。
例子
:
public class BubbleSort {
public static void bubbleSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - 1 - i; j++) { if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}

public static void main(String[] args) {
int[] arr = {5, 3, 8, 4, 2};
bubbleSort(arr);
System.out.println(Arrays.toString(arr)); // 输出: [2, 3, 4, 5, 8]
}
}
2. 选择排序
原理
:选择排序通过在未排序的数列中找到最小(或最大)元素,存放到排序序列的起始位置,然后再从剩余未排序元素中继续寻找最小(或最大)元素,以此类推。
例子
:
public class SelectionSort {
public static void selectionSort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n - 1; i++) { int minIndex = i; for (int j = i + 1; j < n; j++) { if (arr[j] < arr[minIndex]) { minIndex = j; } } int temp = arr[minIndex]; arr[minIndex] = arr[i]; arr[i] = temp; } } public static void main(String[] args) { int[] arr = {5, 3, 8, 4, 2}; selectionSort(arr); System.out.println(Arrays.toString(arr)); // 输出: [2, 3, 4, 5, 8] } } 3. 插入排序 原理 :插入排序通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。 例子 : public class InsertionSort { public static void insertionSort(int[] arr) { int n = arr.length; for (int i = 1; i < n; i++) { int key = arr[i]; int j = i - 1; while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j – 1;
}
arr[j + 1] = key;
}
}

public static void main(String[] args) {
int[] arr = {5, 3, 8, 4, 2};
insertionSort(arr);
System.out.println(Arrays.toString(arr)); // 输出: [2, 3, 4, 5, 8]
}
}
4. 快速排序
原理
:快速排序通过选择一个基准元素,将数组分为两部分,左边部分所有元素都不大于基准元素,右边部分所有元素都不小于基准元素,然后递归地对这两部分进行快速排序。
例子
:
public class QuickSort {
public static void quickSort(int[] arr, int low, int high) {
if (low < high) { int pi = partition(arr, low, high); quickSort(arr, low, pi - 1); quickSort(arr, pi + 1, high); } } private static int partition(int[] arr, int low, int high) { int pivot = arr[high]; int i = (low - 1); for (int j = low; j < high; j++) { if (arr[j] < pivot) { i++; int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } } int temp = arr[i + 1]; arr[i + 1] = arr[high]; arr[high] = temp; return i + 1; } public static void main(String[] args) { int[] arr = {5, 3, 8, 4, 2}; quickSort(arr, 0, arr.length - 1); System.out.println(Arrays.toString(arr)); // 输出: [2, 3, 4, 5, 8] } } 5. 归并排序 原理 :归并排序通过将数组分成两半,分别对这两半进行归并排序,然后将排序好的两半合并成一个有序数组。 例子 : public class MergeSort { public static void mergeSort(int[] arr, int l, int r) { if (l < r) { int m = (l + r) / 2; mergeSort(arr, l, m); mergeSort(arr, m + 1, r); merge(arr, l, m, r); } } private static void merge(int[] arr, int l, int m, int r) { int n1 = m - l + 1; int n2 = r - m; int[] L = new int[n1]; int[] R = new int[n2]; for (int i = 0; i < n1; ++i) L[i] = arr[l + i]; for (int j = 0; j < n2; ++j) R[j] = arr[m + 1 + j]; int i = 0, j = 0; int k = l; while (i < n1 && j < n2) { if (L[i] <= R[j]) { arr[k] = L[i]; i++; } else { arr[k] = R[j]; j++; } k++; } while (i < n1) { arr[k] = L[i]; i++; k++; } while (j < n2) { arr[k] = R[j]; j++; k++; } } public static void main(String[] args) { int[] arr = {5, 3, 8, 4, 2}; mergeSort(arr, 0, arr.length - 1); System.out.println(Arrays.toString(arr)); // 输出: [2, 3, 4, 5, 8] } } 二、查找算法 1. 线性查找 原理 :线性查找通过遍历整个数组,逐个比较元素,直到找到目标元素。 例子 : public class LinearSearch { public static int linearSearch(int[] arr, int x) { for (int i = 0; i < arr.length; i++) { if (arr[i] == x) return i; } return -1; } public static void main(String[] args) { int[] arr = {5, 3, 8, 4, 2}; int x = 4; int result = linearSearch(arr, x); if (result == -1) System.out.println("Element not present"); else System.out.println("Element found at index " + result); // 输出: Element found at index 3 } } 2. 二分查找 原理 :二分查找适用于有序数组,通过不断将数组分成两半,比较中间元素与目标元素的大小,逐步缩小查找范围。 例子 : public class BinarySearch { public static int binarySearch(int[] arr, int x) { int l = 0, r = arr.length - 1; while (l <= r) { int m = l + (r - l) / 2; if (arr[m] == x) return m; if (arr[m] < x) l = m + 1; else r = m - 1; } return -1; } public static void main(String[] args) { int[] arr = {2, 3, 4, 5, 8}; int x = 4; int result = binarySearch(arr, x); if (result == -1) System.out.println("Element not present"); else System.out.println("Element found at index " + result); // 输出: Element found at index 2 } } 三、递归算法 递归是一种重要的算法设计方法,通过函数调用自身来解决问题。 例子 :计算阶乘 public class Factorial { public static int factorial(int n) { if (n == 0) return 1; return n * factorial(n - 1); } public static void main(String[] args) { int n = 5; System.out.println("Factorial of " + n + " is " + factorial(n)); // 输出: Factorial of 5 is 120 } } 四、动态规划 动态规划通过将复杂问题分解成更小的子问题,并存储子问题的解,避免重复计算。 例子 :斐波那契数列 public class Fibonacci { public static int fibonacci(int n) { int[] dp = new int[n + 1]; dp[0] = 0; dp[1] = 1; for (int i = 2; i <= n; i++) { dp[i] = dp[i - 1] + dp[i - 2]; } return dp[n]; } public static void main(String[] args) { int n = 10; System.out.println("Fibonacci number at position " + n + " is " + fibonacci(n)); // 输出: Fibonacci number at position 10 is 55 } } 五、图算法 1. 深度优先搜索(DFS) 原理 :DFS通过递归或栈的方式,从起始节点开始,沿着一条路径尽可能深地搜索,直到无法继续为止,然后回溯。 例子 : import java.util.*; public class DFS { private LinkedList adjLists[];
private boolean visited[];

public DFS(int nodes) {
adjLists = new LinkedList[nodes];
visited = new boolean[nodes];
for (int i = 0; i < nodes; i++) adjLists[i] = new LinkedList();
}

public void addEdge(int src, int dest) {
adjLists[src].add(dest);
}

public void DFS(int node) {
visited[node] = true;
System.out.print(node + ” “);

Iterator i = adjLists[node].listIterator();
while (i.hasNext()) {
int n = i.next();
if (!visited[n])
DFS(n);
}
}

public static void main(String[] args) {
DFS g = new DFS(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 3);

System.out.println(“Following is the Depth First Traversal”);
g.DFS(0); // 输出: 0 1 2 3
}
}
2. 广度优先搜索(BFS)
原理
:BFS通过队列的方式,从起始节点开始,逐层遍历节点,直到遍历完所有节点。
例子
:
import java.util.*;

public class BFS {
private LinkedList adjLists[];
private boolean visited[];

public BFS(int nodes) {
adjLists = new LinkedList[nodes];
visited = new boolean[nodes];
for (int i = 0; i < nodes; i++) adjLists[i] = new LinkedList();
}

public void addEdge(int src, int dest) {
adjLists[src].add(dest);
}

public void BFS(int startNode) {
Queue queue = new LinkedList();
visited[startNode] = true;
queue.add(startNode);

while (!queue.isEmpty()) {
int node = queue.poll();
System.out.print(node + ” “);

Iterator i = adjLists[node].listIterator();
while (i.hasNext()) {
int n = i.next();
if (!visited[n]) {
visited[n] = true;
queue.add(n);
}
}
}
}

public static void main(String[] args) {
BFS g = new BFS(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 3);

System.out.println(“Following is the Breadth First Traversal”);
g.BFS(0); // 输出: 0 1 2 3
}
}
六、贪心算法
贪心算法通过每一步选择当前状态下最优的选择,期望通过局部最优达到全局最优。
例子
:活动选择问题
public class ActivitySelection {
public static void printMaxActivities(int[] start, int[] end, int n) {
int i, j;

System.out.println(“Selected activities are:”);

i = 0;
System.out.print(i + ” “);

for (j = 1; j < n; j++) { if (start[j] >= end[i]) {
System.out.print(j + ” “);
i = j;
}
}
}

public static void main(String[] args) {
int[] start = {1, 3, 0, 5, 8, 5};
int[] end = {2, 4, 6, 7, 9, 9};
int n = start.length;

printMaxActivities(start, end, n); // 输出: Selected activities are: 0 1 3 4
}
}
七、分治算法
分治算法通过将问题分解成若干个小问题,递归解决小问题,然后将小问题的解合并成原问题的解。
例子
:快速排序(已在排序算法中介绍)
八、回溯算法
回溯算法通过试错的方式逐步寻找问题的解,当发现当前路径无法解决问题时,回溯到上一个状态,继续寻找其他路径。
例子
:N皇后问题
public class NQueens {
private int[][] board;
private int size;

public NQueens(int n) {
size = n;
board = new int[n][n];
}

public boolean solveNQ() {
if (!solveNQUtil(0)) {
System.out.println(“Solution does not exist”);
return false;
}
printSolution();
return true;
}

private boolean solveNQUtil(int col) {
if (col >= size)
return true;

for (int i = 0; i < size; i++) { if (isSafe(i, col)) { board[i][col] = 1; if (solveNQUtil(col + 1)) return true; board[i][col] = 0; } } return false; } private boolean isSafe(int row, int col) { int i, j; for (i = 0; i < col; i++) if (board[row][i] == 1) return false; for (i = row, j = col; i >= 0 && j >= 0; i–, j–)
if (board[i][j] == 1)
return false;

for (i = row, j = col; j >= 0 && i < size; i++, j--) if (board[i][j] == 1) return false; return true; } private void printSolution() { for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) System.out.print(" " + board[i][j] + " "); System.out.println(); } } public static void main(String[] args) { NQueens nQueens = new NQueens(4); nQueens.solveNQ(); } } 结语 通过本文的详细讲解和实例代码,相信你已经对Java中的基本算法和数据结构有了更深入的理解。掌握这些核心技能,不仅能提升你的编程能力,还能为你在面试和实际开发中打下坚实的基础。继续练习和探索,你将成为一名优秀的Java开发者!