从基础到进阶:一文掌握排序、查找、动态规划与图算法的全面实现(C++代码实例解析)

server/2025/2/11 8:12:43/
引言

算法是计算机科学的核心,也是程序员解决复杂问题的利器。从基础的排序与查找到进阶的动态规划与图论算法,掌握这些技能不仅是提升编程能力的必经之路,更是解决实际问题的根本。本篇文章将通过 C++ 实现多个经典算法,包括排序、二分查找、动态规划、深度优先搜索(DFS)与 Dijkstra 最短路径算法,助你从基础入门到进阶精通。


第一部分:基础算法

1.1 冒泡排序:从无序到有序的第一步

冒泡排序是一个简单的排序算法,通过不断比较相邻元素并交换位置,将较大的元素“冒泡”到右侧。

代码实现:
 
#include <iostream>
#include <vector>
using namespace std;void bubbleSort(vector<int>& arr) {int n = arr.size();for (int i = 0; i < n - 1; i++) {for (int j = 0; j < n - i - 1; j++) {if (arr[j] > arr[j + 1]) {swap(arr[j], arr[j + 1]);}}}
}int main() {vector<int> arr = {64, 34, 25, 12, 22, 11, 90};cout << "排序前的数组: ";for (int num : arr) cout << num << " ";cout << endl;bubbleSort(arr);cout << "排序后的数组: ";for (int num : arr) cout << num << " ";cout << endl;return 0;
}
1.2 二分查找:高效定位目标的秘诀

二分查找是一种高效的查找算法,适用于有序数组。通过逐步缩小查找范围,可以在 O(log⁡n)O(logn) 的时间复杂度内定位目标值。

代码实现:
 
#include <iostream>
#include <vector>
using namespace std;int binarySearch(const vector<int>& arr, int target) {int left = 0, right = arr.size() - 1;while (left <= right) {int mid = left + (right - left) / 2;if (arr[mid] == target) return mid;else if (arr[mid] < target) left = mid + 1;else right = mid - 1;}return -1; // 未找到目标
}int main() {vector<int> arr = {2, 3, 4, 10, 40};int target = 10;int result = binarySearch(arr, target);if (result != -1) {cout << "目标值 " << target << " 在索引 " << result << " 处" << endl;} else {cout << "目标值 " << target << " 未找到" << endl;}return 0;
}


第二部分:进阶算法

2.1 动态规划:解决 0/1 背包问题

动态规划是一种通过记录子问题结果来避免重复计算的优化算法。在 0/1 背包问题中,我们利用动态规划求解在给定背包容量下,如何选择物品以最大化价值。

代码实现:
 
#include <iostream>
#include <vector>
using namespace std;int knapsack(int W, const vector<int>& weight, const vector<int>& value, int n) {vector<vector<int>> dp(n + 1, vector<int>(W + 1, 0));for (int i = 1; i <= n; i++) {for (int w = 1; w <= W; w++) {if (weight[i - 1] <= w) {dp[i][w] = max(dp[i - 1][w], dp[i - 1][w - weight[i - 1]] + value[i - 1]);} else {dp[i][w] = dp[i - 1][w];}}}return dp[n][W];
}int main() {int W = 50;vector<int> weight = {10, 20, 30};vector<int> value = {60, 100, 120};int n = weight.size();cout << "背包的最大价值: " << knapsack(W, weight, value, n) << endl;return 0;
}
2.2 图算法:Dijkstra 最短路径

Dijkstra 是经典的单源最短路径算法,适合无负权边的图。我们通过优先队列实现高效的路径计算。

代码实现:
 
#include <iostream>
#include <vector>
#include <queue>
#include <climits>
using namespace std;const int INF = INT_MAX;void dijkstra(int start, const vector<vector<pair<int, int>>>& graph, vector<int>& distance) {int n = graph.size();distance.assign(n, INF);distance[start] = 0;priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> pq;pq.push({0, start});while (!pq.empty()) {int currentDist = pq.top().first;int currentNode = pq.top().second;pq.pop();if (currentDist > distance[currentNode]) continue;for (auto& edge : graph[currentNode]) {int nextNode = edge.first;int weight = edge.second;if (distance[currentNode] + weight < distance[nextNode]) {distance[nextNode] = distance[currentNode] + weight;pq.push({distance[nextNode], nextNode});}}}
}int main() {int n = 5;vector<vector<pair<int, int>>> graph(n);graph[0].push_back({1, 10});graph[0].push_back({4, 5});graph[1].push_back({2, 1});graph[2].push_back({3, 4});graph[4].push_back({1, 3});graph[4].push_back({2, 9});graph[4].push_back({3, 2});vector<int> distance;dijkstra(0, graph, distance);cout << "从节点 0 出发到其他节点的最短距离: " << endl;for (int i = 0; i < distance.size(); i++) {cout << "节点 0 到节点 " << i << " 的距离: " << (distance[i] == INF ? -1 : distance[i]) << endl;}return 0;
}


http://www.ppmy.cn/server/166699.html

相关文章

flask开发的网站,后端服务关闭后,可以找回之前的数据的吗

如果使用 Flask 开发的网页&#xff0c;后端服务关闭后&#xff0c;是否还能找回数据取决于数据的存储方式&#xff1a; 可能找回数据的情况&#xff1a; 数据库存储&#xff08;MySQL、PostgreSQL、SQLite 等&#xff09; 如果 Flask 连接的是持久化数据库&#xff0c;即使后…

DeepSeek 使用建议笔记

跟风学习一下~ ------------ Deepseek可以做什么&#xff1f; 参考 《DeepSeek指导手册(24页)》 《DeepSeek&#xff1a;从入门到精通》

python基础入门:4.4模块与包管理

Python模块与包管理完全指南&#xff1a;构建可维护的代码结构 # 示例项目结构 """ my_package/ ├── __init__.py ├── core/ │ ├── __init__.py │ ├── utils.py │ └── calculator.py ├── data/ │ └── config.json └── tes…

[笔记.AI]deepseek-r1的不同版本(满血版、蒸馏版、量化)

满血版&#xff1a;是原始的高性能模型&#xff1b; 蒸馏版&#xff08;Distill&#xff09;&#xff1a;是指将大型模型&#xff08;教师模型&#xff09;的知识转移到较小的模型&#xff08;学生模型&#xff09;中&#xff0c;以保持性能的同时减少计算资源的需求&#xff1…

【Spring】什么是Spring?

什么是Spring&#xff1f; Spring是一个开源的轻量级框架&#xff0c;是为了简化企业级开发而设计的。我们通常讲的Spring一般指的是Spring Framework。Spring的核心是控制反转(IoC-Inversion of Control)和面向切面编程(AOP-Aspect-Oriented Programming)。这些功能使得开发者…

Maven 和 CI/CD 集成:自动化构建与部署

1. Maven 在 CI/CD 中的作用 Maven 是 Java 生态中的标准构建工具&#xff0c;在 持续集成&#xff08;CI&#xff09; 和 持续部署&#xff08;CD&#xff09; 过程中&#xff0c;Maven 负责&#xff1a; 自动化构建&#xff1a;编译 Java 代码、运行测试、打包 JAR/WAR。依…

MYSQL学习笔记(七):新年第一篇之子查询

前言&#xff1a; 祝大家新年快乐 &#x1f386;​&#x1f386;​&#x1f386;​&#x1f386;​&#x1f386;​&#x1f386;​学习和使用数据库可以说是程序员必须具备能力&#xff0c;这里将更新关于MYSQL的使用讲解&#xff0c;大概应该会更新30篇&#xff0c;涵盖入门…

【数据结构】(7) 栈和队列

一、栈 Stack 1、什么是栈 栈是一种特殊的线性表&#xff0c;它只能在固定的一端&#xff08;栈顶&#xff09;进行出栈、压栈操作&#xff0c;具有后进先出的特点。 2、栈概念的例题 答案为 C&#xff0c;以C为例进行讲解&#xff1a; 第一个出栈的是3&#xff0c;那么 1、…