东方博宜OJ 1010:数组元素的排序 ← 直接插入排序
【题目来源】
https://oj.czos.cn/p/1010
【题目描述】
对数组的元素按从小到大进行排序。
【输入格式】
第一行有一个整数 n(5≤n≤10);
第二行有 n 个整数,每个整数的值在 [0, 10^9]的范围内。
【输出格式】
输出排序后的数组。
【输入样例】
8
1 2 3 6 8 7 4 5
【输出样例】
1 2 3 4 5 6 7 8
【数据范围】
5≤n≤10
【算法分析】
插入排序的基本思想是:每次将一个待排序的记录,按其关键字大小插入到前面已经排好序的一组记录中的适当位置,直到所有待排序记录全部插入为止。
【算法代码】
#include <bits/stdc++.h>
using namespace std;
const int N=15;
int a[N];
int n;
int main() {
cin>>n;
for(int i=1; i<=n; i++) cin>>a[i];
for(int i=1; i<=n; i++) {
int t=a[i];
int j=i-1;
while(j>=0 && a[j]>t) {
a[j+1]=a[j];
j--;
}
a[j+1]=t;
}
for(int i=1; i<=n; i++) cout<<a[i]<<" ";
return 0;
}
/*
in:
5
6 9 2 7 1
out:
1 2 6 7 9
*/
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/121733509
https://www.luogu.com.cn/problem/solution/P7910
© 版权声明
文章版权归作者所有,未经允许请勿转载。