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)343
- Python实现多个整数相乘的计算及开发建议(字节豆包 | 427点数解答 | 2026-02-25 19:25:10)25
- 编程求解 1 到 N 的阶乘和:Python 与 C++ 实现(字节豆包 | 650点数解答 | 2026-03-01 20:05:48)14
- 易语言读取文本文件并显示到超级列表框:代码示例与注意要点(DeepSeek | 571点数解答 | 2025-08-23 20:54:40)224
- 易语言:读取并显示特定文本到超级列表框,还能增加新数据的方法与要点(DeepSeek | 1317点数解答 | 2025-08-23 20:58:40)230
- 哈夫曼编码:基于字符频率实现(0,1)编码及Python代码详解(讯飞星火 | 794点数解答 | 2024-06-19 23:42:13)232
- C++求解序列或与运算和差值:避O(nq)复杂度及数据处理要点(字节豆包 | 534点数解答 | 2025-10-17 20:05:07)60
- C++ 实现:从大整数中删数求最小密码的巧妙算法(DeepSeek | 473点数解答 | 2025-06-20 16:08:21)195
- C++ 实现我的世界基岩版:从简单框架到开发要点揭秘(字节豆包 | 182点数解答 | 2025-02-22 15:53:11)195
- C++ 实现完整斗地主:含洗牌、发牌与手牌展示,可按需扩展!(字节豆包 | 1028点数解答 | 2026-01-10 08:02:37)36
- 51 单片机:定时器 0 实现 8 个 LED 循环点亮,附代码及优化建议(字节豆包 | 1193点数解答 | 2024-12-27 15:10:29)310
- Java 实现:轻松生成 5 位数字、大小写字母混合验证码( | 266点数解答 | 2024-03-06 17:39:10)329