// 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]]
Code Example |
---|
Cpp :: c++ erase remove |
Cpp :: descending order c++ |
Cpp :: c++ base constructor |
Cpp :: macros in c++ |
Cpp :: c++ Program to check if a given year is leap year |
Cpp :: word equation numbers |
Cpp :: input n space separated integers in c++ |
Cpp :: quicksort |
Cpp :: std::copy C ++ |
Cpp :: cpp array init value |
Cpp :: c++ #define |
Cpp :: how to concatenate two vectors in c++ |
Cpp :: for loop in cpp |
Cpp :: set size in c++ |
Cpp :: map count function c++ |
Cpp :: how to add space in c++ |
Cpp :: c++ vector first element |
Cpp :: c++ insert variable into string |
Cpp :: changing values of mat in opencv c++ |
Cpp :: c++ fill two dimensional array |
Cpp :: how to convert hexadecimal to decimal in c++ |
Cpp :: c++ delay |
Cpp :: C++ if...else...else if |
Cpp :: google test assert throw |
Cpp :: c++ list of pairs |
Cpp :: assign one vector to another c++ |
Cpp :: int to string C++ Using stringstream class |
Cpp :: c++ string to char* |
Cpp :: definition of singly linkedlist |
Cpp :: declare class c++ |