Skip to content

Instantly share code, notes, and snippets.

@maurcarvalho
Created December 26, 2013 17:48
Show Gist options
  • Save maurcarvalho/8136587 to your computer and use it in GitHub Desktop.
Save maurcarvalho/8136587 to your computer and use it in GitHub Desktop.
static void insertionSort(int[] ar) {
//variavel responsavel por conter o valor do ultimo indice.
int lastIndex;
//variavel auxiliar para conter o valor do elemento corrente.
int key;
for(int j = 1; j < ar.length; j++){
//atribuindo valor elemento corrente.
key = ar[j];
//atribuindo valor do ultimo elemento.
lastIndex = j - 1;
/*intere enquanto o ultimo indice for >=0 e o
ultimo elemento for maior que o elemento corrente.
*/
while (lastIndex >= 0 && ar[lastIndex] > key) {
//atribui o elemento anterior na proxima posicao.
ar[lastIndex+1] = ar[lastIndex];
lastIndex -= 1;
}
ar[lastIndex+1] = key;
}
printArray(ar);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment