#include <iostream>
#include <vector>
using namespace std;
//this function just displays the vector
void display(vector<int> v)
{
for (int i=0;i<v.size();i++)
cout << v[i] << " ";
cout << endl;
}
//This function performs the actual sortin'
void insertionSort(vector<int> &a)
{
int i, j, key;
//don't have to start from very first element, as one element is
//considered already sorted.
for (i=1;i<a.size();i++)
{
//make copy of the current element.
key = a[i];
//run through previous elements, to find a space. As long as elements
//are greater than current element keep shifting them
for(j=i-1;j>=0 && a[j]>key; j--)
a[j+1]=a[j];
//when out of loop, j is the element before where key has to be
//inserted. Copy key in correct location.
a[j+1] = key;
cout << "After step " << i << ": ";
display(a);
}
}
int main()
{
vector<int> v(5);
v[0]=50;
v[1]=40;
v[2]=10;
v[3]=30;
v[4]=20;
cout << "Original Array: ";
display(v);
insertionSort(v);
}
|