关键知识点第3章插入排序法3.2

时间:2020-05-13 19:50:43   收藏:0   阅读:50

输入

6

5 2 4 6 1 3

输出

1 2 3 4 5 6

 

代码

#include<iostream>
using namespace std;
void insertionsort(int a[],int n) {
int i, j, temp;
for (int i = 1;i < n;i++) {//从1开始的原因是可以把a【0】看作是有序的 所以不用再给它排序了
temp = a[i];
j = i - 1;
while (j >= 0 && a[j] > temp) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = temp;
}

}
int main() {
int n;
int a[100];
cin >> n;
for (int i = 0;i < n;i++)
cin >> a[i];
insertionsort(a, n);
for (int i = 0;i < n;i++) {
cout << a[i] << " ";
}
return 0;
}

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!