insertion sorty code example
Example 1: insertion sort java
Insertion program
public class InsertionSortExample
{
public void sort(int[] arrNum)
{
int number = arrNum.length;
for(int a = 1; a < number; ++a)
{
int keyValue = arrNum[a];
int b = a - 1;
while(b >= 0 && arrNum[b] > keyValue)
{
arrNum[b + 1] = arrNum[b];
b = b - 1;
}
arrNum[b + 1] = keyValue;
}
}
static void displayArray(int[] arrNum)
{
int num = arrNum.length;
for(int a = 0; a < num; ++a)
{
System.out.print(arrNum[a] + " ");
}
System.out.println();
}
public static void main(String[] args)
{
int[] arrInput = { 50, 80, 10, 30, 90, 60 };
InsertionSortExample obj = new InsertionSortExample();
obj.sort(arrInput);
displayArray(arrInput);
}
}
Example 2: insertion sort
def insertionSort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j >= 0 and key < arr[j] :
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = key
Example 3: insertion sort
function insertionSort(vetor) {
let current;
for (let i = 1; i < vetor.length; i += 1) {
let j = i - 1;
current = vetor[i];
while (j >= 0 && current < vetor[j]) {
vetor[j + 1] = vetor[j];
j--;
}
vetor[j + 1] = current;
}
return vetor;
}
insertionSort([1, 2, 5, 8, 3, 4])
Example 4: Insertion sort algorithm
INSERTION-SORT(A)
for i = 1 to n
key ← A [i]
j ← i – 1
while j > = 0 and A[j] > key
A[j+1] ← A[j]
j ← j – 1
End while
A[j+1] ← key
End for
Example 5: insertion sort
function insertionSortIterativo(array A)
for i ← 1 to length[A]
do value ← A[i]
j ← i-1
while j >= 0 and A[j] > value
do A[j + 1] ← A[j]
j ← j-1
A[j+1] ← value;