6种排序算法完整实现:自行编码、复杂度分析与运行时间对比
以下是冒泡排序的 C++ 代码实现: ```cpp #include <iostream> using namespace std; // 冒泡排序函数 void bubbleSort(int arr[], int n) { int temp; int swapCount = 0; for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; cout << "Swap " << swapCount << " : " << arr[j] << " and " << arr[j + 1] << endl; swapCount++; } } cout << "Iteration " << i << endl; } cout << "Total swaps: " << swapCount << endl; } // 打印数组函数 void printArray(int arr[], int size) { for (int i = 0; i < size; i++) cout << arr[i] << " "; cout << endl; } // 测试案例 int main() { int arr[] = {70, 33, -59, 16, -56, 63, 80, -21, 75, -5, 90, -4, 72, -61, -39, -97, 44, 9, 18, 14}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Bubble Sort" << endl; bubbleSort(arr, n); cout << "Sorted array: "; printArray(arr, n); return 0; } ``` 以下是直接插入排序的 C++ 代码实现: ```cpp #include <iostream> using namespace std; // 直接插入排序函数 void insertionSort(int arr[], int n) { int key, j; for (int i = 1; i < n; i++) { key = arr[i]; j = i - 1; while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; cout << "Number " << arr[i] << " inserts at position " << j + 1 << endl; } } // 打印数组函数 void printArray(int arr[], int size) { for (int i = 0; i < size; i++) cout << arr[i] << " "; cout << endl; } // 测试案例 int main() { int arr[] = {70, 33, -59, 16, -56, 63, 80, -21, 75, -5, 90, -4, 72, -61, -39, -97, 44, 9, 18, 14}; int n = sizeof(arr) / sizeof(arr[0]); cout << "Insertion Sort" << endl; insertionSort(arr, n); cout << "Sorted array: "; printArray(arr, n); return 0; } ``` 额外需要注意的逻辑点: 1. 注意代码中的边界情况,例如数组为空或只有一个元素的情况。 2. 对于排序算法的时间和空间复杂度的分析要准确。 3. 确保代码的可读性和可维护性,添加必要的注释。 ######[AI写代码神器 | 859点数解答 | 2025-01-10 13:19:29]
- Python 实现球类:精准计算半径、表面积与体积,附输入验证与异常处理!(阿里通义 | 261点数解答 | 2024-11-28 21:19:39)378
- 哈夫曼编码:基于字符频率实现(0,1)编码及Python代码详解(讯飞星火 | 794点数解答 | 2024-06-19 23:42:13)249
- C++求解序列或与运算和差值:避O(nq)复杂度及数据处理要点(字节豆包 | 534点数解答 | 2025-10-17 20:05:07)74
- Python实现多个整数相乘的计算及开发建议(字节豆包 | 427点数解答 | 2026-02-25 19:25:10)45
- 编程求解 1 到 N 的阶乘和:Python 与 C++ 实现(字节豆包 | 650点数解答 | 2026-03-01 20:05:48)26
- C++实现自定义函数计算 f(a)+f(b)+f(c)(字节豆包 | 610点数解答 | 2026-04-11 20:22:28)22
- C++实现找出指定范围内完全数的方法及开发建议(字节豆包 | 692点数解答 | 2026-04-11 20:23:34)20
- C++ 计算 1 到 n 中数字 1 的出现次数的实现与解析(字节豆包 | 849点数解答 | 2026-04-11 20:24:18)25
- C++ 实现我的世界基岩版:从简单框架到开发要点揭秘(字节豆包 | 182点数解答 | 2025-02-22 15:53:11)214
- C++ 实现完整斗地主:含洗牌、发牌与手牌展示,可按需扩展!(字节豆包 | 1028点数解答 | 2026-01-10 08:02:37)56
- C++ 实现:从大整数中删数求最小密码的巧妙算法(DeepSeek | 473点数解答 | 2025-06-20 16:08:21)212
- 易语言读取文本文件并显示到超级列表框:代码示例与注意要点(DeepSeek | 571点数解答 | 2025-08-23 20:54:40)259