-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathInsertion.java
60 lines (51 loc) · 2.07 KB
/
Insertion.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
//==============//
//INSERTION SORT//
//==============//
package Sorting;
import java.util.Random;
public class Insertion {
public static void main(String[] args) {
System.out.println("\n#================#");
System.out.println("| INSERTION SORT |");
System.out.println("#================#\n");
// criacao do array
int[] array = new int[10];
// preenchimento do array com numeros aleatorios de 10 a 99
for (int i = 0; i < array.length; i++){
array[i] = (int) (new Random().nextInt(90) + 10);
}
// imprime o vetor desordenado
System.out.println("Vetor desordenado:");
System.out.println("*-------------------------------------------------*");
for (int i = 0; i < array.length; i++){
System.out.print("| " + array[i] + " ");
}
System.out.println("|");
System.out.println("*-------------------------------------------------*\n");
//=====INSERTION SORT=====//
// variaveis auxiliares
int j;
// controlador
for (int i = 1; i < array.length; i++){
// define j como elemento a esquerda do controlador
j = i-1;
// comparador (roda SE e ENQUANTO achar um elemento menor a direita)
while((j >= 0) && (array[j] > array[j+1])){
// funcao swap (reordena a parte a esquerda do comparador)
int aux = array[j];
array[j] = array[j+1];
array[j+1] = aux;
j--;
}
}
//=====INSERTION SORT=====//
// imprime o vetor ordenado
System.out.println("Vetor ordenado apos o sort:");
System.out.println("*-------------------------------------------------*");
for (int i = 0; i < array.length; i++){
System.out.print("| " + array[i] + " ");
}
System.out.println("|");
System.out.println("*-------------------------------------------------*\n");
}
}