题目
略
思路
正常插入排序,需要注意在每一趟比较中a[j - 1] > tmp
需要写进for循环判断语句,以获取目标j
的位置
代码
#include<bits/stdc++.h>
using namespace std;
void insertionSort(int* a, int n)
{
for (int p = 1; p < n; p++)
{
int tmp = a[p];
int j = p;
for (; j >= 0 && a[j - 1] > tmp; j--)
{
a[j] = a[j - 1];
}
//cout << j << endl;
a[j] = tmp;
for (int i = 0; i < n-1; i++)
cout << a[i] << ' ';
cout << a[n-1] << endl;
}
}
int main()
{
int n; cin >> n;
int* a = new int[n];
for (int i = 0; i < n; i++)
cin >> a[i];
insertionSort(a, n);
return 0;
};