Sort a list in ascending order with "insertion sort" method.
Input:
Input integer n at first line, where 1<=n<=10. Then input a list of n integer numbers.
Output:
print out the list state after each pass.
Input Example:
Here is a set of inputs. For example:
6
8 4 7 5 9 6
Output Example:
The corresponding output is given here.
Note that there is a space at the end of each line.
4 8 7 5 9 6
4 7 8 5 9 6
4 5 7 8 9 6
4 5 7 8 9 6
4 5 6 7 8 9
#include<iostream>
#include<stdio.h>
#include <cstdlib>
using namespace std;
int main()
{
int n;
cin >> n;
int* a = new int[n];
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
if(n==1)
{
cout<<a[0]<<" "<<endl;
}
else
{
for (int j = 1; j < n; j++)
{
int key = a[j];
int i = j - 1;
while (i >= 0 && a[i] > key)
{
a[i + 1] = a[i];
i--;
}
a[i + 1] = key;
for (int k = 0; k < n; k++)
{
cout << a[k] << " ";
}
cout << endl;
}
}
delete[] a;
return 0;
}