题解
【入门】数组元素的排序
1 条题解
-
0
解题思路
按照题目要求直接计算。代码中使用简单的循环、判断和数组,把每一步写出来,方便理解。
参考代码
// 读取题目给出的数据。 // 按照题意完成计算。 // 输出最终答案。 #include <iostream> using namespace std; int main() { int n, a[15]; cin >> n; for (int i = 0; i < n; i++) cin >> a[i]; for (int i = 0; i < n; i++) { for (int j = 0; j + 1 < n - i; j++) { if (a[j] > a[j + 1]) { int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t; } } } for (int i = 0; i < n; i++) { if (i) cout << " "; cout << a[i]; } cout << endl; return 0; }复杂度
代码只使用了题目需要的循环、判断和数组。若有 n 次循环,时间复杂度为 O(n);只使用固定数量变量时,空间复杂度为 O(1)。
- 1