酷代码 AI
菜单
服务商

C++ 随机数组生成与插入排序算法的代码修正与实现

It looks like you're trying to implement a sorting algorithm in C++. However, there are several issues with your code that need to be addressed: 1. The `getrand` function is incorrectly defined. 2. There are missing closing braces for the `set` and `show` functions. 3. The `insertsort` function is not implemented. 4. There are syntax errors in the `main` function. 5. The `cout` statement in the `show` function should have a space between the elements. Here's a corrected version of your code with an implementation of the insertion sort algorithm: ```cpp #include <iostream> #include <cstdlib> #include <ctime> using namespace std; const int n = 10; const int min = 10; const int max = 99; int getrand(int min, int max) { return (rand() % (max - min + 1)) + min; } void set(int r[], int n) { for (int i = 0; i < n; i++) { r[i] = getrand(min, max); } } void show(int r[], int n) { for (int i = 0; i < n; i++) { cout << r[i] << " "; } cout << endl; } void insertsort(int r[], int n) { for (int i = 1; i < n; i++) { int key = r[i]; int j = i - 1; while (j >= 0 && r[j] > key) { r[j + 1] = r[j]; j--; } r[j + 1] = key; } } int main() { srand(time(0)); int a[n]; set(a, n); cout << "原序列: "; show(a, n); cout << "新序列: \n"; insertsort(a, n); show(a, n); return 0; } ``` Explanation: 1. Function Definitions: - `getrand`: Generates a random number between `min` and `max`. - `set`: Fills an array with random numbers. - `show`: Prints the elements of an array. - `insertsort`: Implements the insertion sort algorithm. 2. Main Function: - Seeds the random number generator using `srand(time(0))`. - Creates an array `a` of size `n`. - Fills the array with random numbers using `set`. - Prints the original sequence. - Sorts the array using `insertsort`. - Prints the sorted sequence. ######[AI写代码神器 | 703点数解答 | 2024-10-31 10:35:24]

相关提问
本站限时免费提问中
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]