Insertion Sort Algorithm
Insertion sort is a simple sorting algorithm that builds the final sorted array one item at a time. It is much less efficient on large lists than more advanced algorithms such as quicksort, heapsort, or merge sort.
http://localhost:3000
- Java
- C++
- JavaScript
class insertionSort{
public static void main(String [] args){
int i,j,current,size;
int a[] = {4,3,2,10,12,1,5,6};
size = a.length;
for(i = 1; i<size; i++){
current = a[i];
j = i- 1;
while(j>=0 && a[j]>current){
a[j+1] = a[j];
j--;
}
a[j+1] = current;
}
for(i = 0; i<a.length; i++){
System.out.print(a[i]+" ");
}
}
}
#include<iostream>
#include<conio.h>
using namespace std;
int main(){
int i,j,current,n,inputnumber;
cout<<"Enter the Total Number"<<endl;
cin>n;
int a[n];
cout<<"Enter the Number ="<<n<<endl;
for(i=0; i<n; i++){
cout<<"a["<<i<<"] = ";
cin>inputnumber;
a[i]=inputnumber;
}
for(i=1; i<n; i++){
current = a[i];
j = i-1;
while(j>=0 && a[j]>current){
a[j+1] = a[j];
j--;
}
a[j+1]=current;
}
cout<<"Insertion Sort = ";
for(i=0; i<n; i++){
cout<<a[i]<<" ";
}
getch();
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Insertion Sort in Java Script</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<label for="input number">Input the Numbers:</label>
<input type="text" id="innumber"/>
<br />
<button onclick="hassan()">click me</button>
<p id="demo"></p>
<script>
//Using Function to Create the Insertion Sort Alogrithm in javaScript.
function hassan(){
var a,i,j,current,size; //Declare the Variables
var a = [30,50,70,50];
size = a.length; //Check size of the Array
for(i=1; i<size; i++){
current = a[i]; //Select the Key Number
j = i-1;
while(j>=0 && a[j]>current){
a[j+1] = a[j];
j--;
}
a[j+1]=current;
}
for(i=0; i<size; i++){
document.getElementById("demo").innerHTML = a;
}
}
</script>
</body>
</html>