// C++ program for insertion sort
#include <bits/stdc++.h>
using namespace std;
/* Function to sort an array using insertion sort*/
void insertionSort(int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && arr[j] > key)
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
// A utility function to print an array of size n
void printArray(int arr[], int n)
{
int i;
for (i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}
/* Driver code */
int main()
{
int arr[] = { 12, 11, 13, 5, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
insertionSort(arr, n);
printArray(arr, n);
return 0;
}
// This is code is contributed by rathbhupendra
#include<bits/stdc++.h>
using namespace std;
int main()
{
//insertion sort
int a[5] = {1,56,94,12,31};
//if(n>1)
int i,j;
for(i=0;i<5-1;i++)
{
for(j=i+1;j>0;j--)
{
if(a[j]>=a[j-1])
{
break;
}
swap(a[j],a[j-1]);
}
}
for(i=0;i<5;i++)
{
cout<<a[i]<<" ";
}
return 0;
}
void insertionSort(int a[], int N) {
for (int i = 1; i < N; ++i) { // O(N)
int X = a[i]; // X is the item to be inserted
int j = i-1;
for (; j >= 0 && a[j] > X; --j) // can be fast or slow
a[j+1] = a[j]; // make a place for X
a[j+1] = X; // index j+1 is the insertion point
}
}
// https://visualgo.net/en/sorting?slide=9-1
// [[29May2022]]