diff --git a/docs/.vitepress/config.mts b/docs/.vitepress/config.mts index 144ac5c..0ef1657 100644 --- a/docs/.vitepress/config.mts +++ b/docs/.vitepress/config.mts @@ -34,6 +34,12 @@ export default defineConfig({ // 配置侧边栏 sidebar:{ + "/408/algorithm/":[ + { + text:"基础算法", + link:"/408/algorithm/" + } + ], "/frontend/":[ { text:"阅读", @@ -81,6 +87,27 @@ export default defineConfig({ text: "前端", link: "/frontend/navigation-bar" }, + { + text: "408", + items:[ + { + text:"数据结构与算法", + link:"/408/algorithm/" + }, + // { + // text:"操作系统", + // link:"." + // }, + // { + // text:"计算机网络", + // link:"." + // }, + // { + // text:"计算机组成原理", + // link:"." + // }, + ] + }, { text: "书签", link: "/bookmarks/" diff --git a/docs/408/algorithm/index.md b/docs/408/algorithm/index.md new file mode 100644 index 0000000..a55b900 --- /dev/null +++ b/docs/408/algorithm/index.md @@ -0,0 +1,46 @@ +--- +layout: doc +outline: [2,3] +--- + +### 二分法 + +二分法是一种常见的搜索算法,通常用于在有序数组或列表中查找特定元素的位置。 +时间复杂度为O(log n),其中n是元素数量 + + +::: code-group + +```text[伪代码] +函数 binary_search(数组 arr, 目标值 target) -> 整数 + 左边界 left 设为 0 + 右边界 right 设为 数组长度 - 1 + + 当 左边界 <= 右边界 时执行: + 中间位置 mid 设为 (左边界 + 右边界) / 2 + + 如果 数组[mid] == target,则返回 mid + 否则如果 数组[mid] < target,则 左边界 设为 mid + 1 + 否则 右边界 设为 mid - 1 + + 返回 -1 // 没有找到目标值 +``` + +```c++[C++] +int binary_search(vector& arr, int target) { + int left = 0; + int 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; // 没有找到目标值 +} +``` + +::: \ No newline at end of file