Skip to content

Commit e927216

Browse files
Create InsertionSort.java
1 parent bde484b commit e927216

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

InsertionSort.java

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import java.util.Arrays;
2+
3+
public class InsertionSort {
4+
5+
//Função para o Insertion Sort
6+
public static void sort(int[] vetor) {
7+
int aux, j;
8+
//Laço de repetição para percorrer a lista
9+
for (int i = 1; i < vetor.length; i++) {
10+
//Auxiliar para melhor leitura
11+
aux = vetor[i];
12+
//Indice do vetor
13+
j = i - 1;
14+
15+
//Enquanto as 2 opções forem Verdadeiras
16+
while(j >= 0 && aux < vetor[j]) {
17+
//O num q estava na posição j+1 vai ocupar a posição j
18+
vetor[j+1] = vetor[j];
19+
//Caso o aux precise andar mais de uma casa para esquerda
20+
j--;
21+
}
22+
vetor[j+1] = aux;
23+
}
24+
}
25+
26+
27+
//Função Principal
28+
public static void main(String[] args) {
29+
//Criação lista 0 1 2 3 4
30+
int[] vetor = { 3, 4, 1, 2, 5 };
31+
32+
//Função para ordenar a lista
33+
sort(vetor);
34+
35+
//Imprimindo a lista Ordenada
36+
System.out.println(Arrays.toString(vetor));
37+
}
38+
}

0 commit comments

Comments
 (0)