// C++ program for insertion sort
#include <string.h>
#include <iostream>
using namespace std;
void printArray(int arr[], int n);
void insertionSort(int arr[], int n);
/* 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;
}
Ly8gQysrIHByb2dyYW0gZm9yIGluc2VydGlvbiBzb3J0CiNpbmNsdWRlIDxzdHJpbmcuaD4KI2luY2x1ZGUgPGlvc3RyZWFtPgoKdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCnZvaWQgcHJpbnRBcnJheShpbnQgYXJyW10sIGludCBuKTsKdm9pZCBpbnNlcnRpb25Tb3J0KGludCBhcnJbXSwgaW50IG4pOwoKIAovKiBGdW5jdGlvbiB0byBzb3J0IGFuIGFycmF5IHVzaW5nIGluc2VydGlvbiBzb3J0Ki8Kdm9pZCBpbnNlcnRpb25Tb3J0KGludCBhcnJbXSwgaW50IG4pCnsKICAgIGludCBpLCBrZXksIGo7CiAgICBmb3IgKGkgPSAxOyBpIDwgbjsgaSsrKQogICAgewogICAgICAgIGtleSA9IGFycltpXTsKICAgICAgICBqID0gaSAtIDE7CiAKICAgICAgICAvKiBNb3ZlIGVsZW1lbnRzIG9mIGFyclswLi5pLTFdLCB0aGF0IGFyZQogICAgICAgIGdyZWF0ZXIgdGhhbiBrZXksIHRvIG9uZSBwb3NpdGlvbiBhaGVhZAogICAgICAgIG9mIHRoZWlyIGN1cnJlbnQgcG9zaXRpb24gKi8KICAgICAgICB3aGlsZSAoaiA+PSAwICYmIGFycltqXSA+IGtleSkKICAgICAgICB7CiAgICAgICAgICAgIGFycltqICsgMV0gPSBhcnJbal07CiAgICAgICAgICAgIGogPSBqIC0gMTsKICAgICAgICB9CiAgICAgICAgYXJyW2ogKyAxXSA9IGtleTsKICAgIH0KfQogCi8vIEEgdXRpbGl0eSBmdW5jdGlvbiB0byBwcmludCBhbiBhcnJheSBvZiBzaXplIG4Kdm9pZCBwcmludEFycmF5KGludCBhcnJbXSwgaW50IG4pCnsKICAgIGludCBpOwogICAgZm9yIChpID0gMDsgaSA8IG47IGkrKykKICAgICAgICBjb3V0IDw8IGFycltpXSA8PCAiICI7CiAgICBjb3V0IDw8IGVuZGw7Cn0KIAovKiBEcml2ZXIgY29kZSAqLwppbnQgbWFpbigpCnsKICAgIGludCBhcnJbXSA9IHsgMTIsIDExLCAxMywgNSwgNiB9OwogICAgaW50IG4gPSBzaXplb2YoYXJyKSAvIHNpemVvZihhcnJbMF0pOwogCiAgICBpbnNlcnRpb25Tb3J0KGFyciwgbik7CiAgICBwcmludEFycmF5KGFyciwgbik7CiAKICAgIHJldHVybiAwOwp9