1Insertion program
2public class InsertionSortExample
3{
4 public void sort(int[] arrNum)
5 {
6 int number = arrNum.length;
7 for(int a = 1; a < number; ++a)
8 {
9 int keyValue = arrNum[a];
10 int b = a - 1;
11 while(b >= 0 && arrNum[b] > keyValue)
12 {
13 arrNum[b + 1] = arrNum[b];
14 b = b - 1;
15 }
16 arrNum[b + 1] = keyValue;
17 }
18 }
19 static void displayArray(int[] arrNum)
20 {
21 int num = arrNum.length;
22 for(int a = 0; a < num; ++a)
23 {
24 System.out.print(arrNum[a] + " ");
25 }
26 System.out.println();
27 }
28 public static void main(String[] args)
29 {
30 int[] arrInput = { 50, 80, 10, 30, 90, 60 };
31 InsertionSortExample obj = new InsertionSortExample();
32 obj.sort(arrInput);
33 displayArray(arrInput);
34 }
35}
1void InsertionSort(int* A, int size)
2{
3
4 int i, key, j;
5 for (i = 1; i < N; i++)
6 {
7 key = A[i];
8 j = i - 1;
9
10 /* Move elements of arr[0..i-1], that are
11 greater than key, to one position ahead
12 of their current position */
13 while (j >= 0 && A[j] > key)
14 {
15 A[j + 1] = A[j];
16 j = j - 1;
17 }
18 A[j + 1] = key;
19 }
20
21}
1// Por ter uma complexidade alta,
2// não é recomendado para um conjunto de dados muito grande.
3// Complexidade: O(n²) / O(n**2) / O(n^2)
4// @see https://www.youtube.com/watch?v=TZRWRjq2CAg
5// @see https://www.cs.usfca.edu/~galles/visualization/ComparisonSort.html
6
7function insertionSort(vetor) {
8 let current;
9 for (let i = 1; i < vetor.length; i += 1) {
10 let j = i - 1;
11 current = vetor[i];
12 while (j >= 0 && current < vetor[j]) {
13 vetor[j + 1] = vetor[j];
14 j--;
15 }
16 vetor[j + 1] = current;
17 }
18 return vetor;
19}
20
21insertionSort([1, 2, 5, 8, 3, 4])