Skip to content

Instantly share code, notes, and snippets.

@ErickGiffoni
Created August 27, 2020 17:58
Show Gist options
  • Save ErickGiffoni/f14c5b36f75a2e79c0c92f4cce05fc5a to your computer and use it in GitHub Desktop.
Save ErickGiffoni/f14c5b36f75a2e79c0c92f4cce05fc5a to your computer and use it in GitHub Desktop.
Using Insertion Sort algorithm to order an array. The numbers are read from stdin while EOF is not reached and the output is put in stdout.
/*
* University of Brasilia - Brazil, UnB
* Software Engineering
* Created by Erick Giffoni in 2020 .
* Copyright © 2020 Erick Giffoni . All rights reserved.
*/
#include <stdio.h>
#define tamanho 50000
void insertionSort(int *v, int esq, int dir);//pointer v to array, left(first) index, right(last) index
int main(){
int vet[tamanho];
int qtd_numeros = 0;
while(scanf(" %d", &vet[qtd_numeros]) != EOF)
qtd_numeros++; //last index, exclusive
insertionSort(vet, 0, qtd_numeros-1);
printf("%d", vet[0]);
for(int i=1; i<qtd_numeros; i++){
printf(" %d", vet[i]);
}
printf("\n");
return 0;
}// end main
void insertionSort(int *v, int esq, int dir){
for(int i=dir; i>esq; i--){
if(v[i]<v[i-1]){
int tmp = v[i];
v[i] = v[i-1];
v[i-1] = tmp;
}
}
for(int i=esq+2; i<=dir; i++){
//note that the initial condition of i assumes that the array has at least 3 positions
int j=i;
int tmp = v[j];
while(tmp<v[j-1]){
v[j] = v[j-1];
j--;
}
v[j] = tmp;
}
}//end insertion sort
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment