Insertion sort
- C++
- Java
- Python
//Insert an element from unsorted array to its corect position
// in sorted array by checking that element with each elements
// of the sorted array using a for loop.
#include <iostream>
#include <vector>
#include <algorithm>
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> v(n);
for (int i = 0; i < n; i++)
{
cin >> v.at(i);
}
//Insertion Sort Algorithm
for (int i = 1; i < n; i++)
{
int j = i - 1;
int current = v.at(i); //v[i] can also be used
while (j >= 0 && v.at(j) > current)
{
j = j - 1;
}
v.at(j + 1) = current;
}
for (auto el : v)
cout << el << " ";
cout << endl;
//<==<==<==<==<==<==STL std::sort()⏩⏩⏩⏩⏩⏩
//also refer ⏩ http://www.cplusplus.com/reference/algorithm/sort/
//also refer ⏩ https://www.geeksforgeeks.org/sort-c-stl/
// sort(v.begin(), v.begin() + n);
// for (auto el : v)
// cout << el << " ";
return 0;
}
import java.util.*;
import java.io.*;
public class InsertionSort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
arr[i] = sc.nextInt();
}
for (int i = 1; i < n; i++) {
int j = i - 1;
int current = arr[i];
while (j >= 0 && arr[j] > current) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = current;
}
for (var el : arr) {
System.out.print(el + " ");
}
sc.close();
}
}
def hello_world():
print 'Hello, world!'