源代码:
#include<iostream>
using namespace std;
int a[10000];
int main()
{
int n = 0;
int b = 0;
while (cin >> b)
a[n++] = b;
for (int i = 1; i < n; ++i)
{
int now = a[i], j;//now拷贝待插牌
for (j = i - 1; j >= 0; --j)
if (a[j] > now)//查找整个有序列,一旦比待插牌大就把后面的值变为当前牌
a[j + 1] = a[j];
else break;//break的是内层for,一旦在有序列中找到了合适的位置就break
a[j + 1] = now;//在寻求的恰当位置插入now
}
for (int i = 0; i < n; ++i)
cout << a[i] << ' ';
return 0;
}
学习心得:
不知道是不是我太笨了,洛谷书对插入排序的描述看了好久才看懂。插入排序比冒泡排序和插入排序都要难理解,但是在复杂度上没有明显优势,只有当数据已经基本有序的情况下插入排序才会有较好的效率。