Estrutura de Dados – Ordenação de Vetor (Insertion Sort) em C

Caros usuários venho expor através deste código a implementação do método
de ordenação de vetores [Insertion Sort] de forma Estática e Dinâmica.

[C]
#include
#include

int vetor[5];
//int vetor[5] = {5, 4, 3, 2, 1};

typedef struct ELista
{
int inf;
struct ELista * prox;
struct ELista * ant;
} TLista;

TLista * lista, *novo, *ultimo, *atual, *anterior;

void primeiro(int informacao)
{
lista = malloc(sizeof (TLista));
lista->inf = informacao;
}

void demais(int informacao)
{
novo = malloc(sizeof (TLista));
novo->inf = informacao;
ultimo = lista;

while (ultimo->prox != NULL)
{
ultimo = ultimo->prox;
}

ultimo->prox = novo;
novo->ant = ultimo;
}

void add(int informacao)
{
if (lista == NULL)
primeiro(informacao);
else
demais(informacao);
}

//Listar Dinâmico
void listarD()
{
ultimo = lista;
while (ultimo != NULL)
{
printf(“%d\n”, ultimo->inf);
ultimo = ultimo->prox;
}
}

//Listar Estático
void listar()
{
int i;
for (i = 0; i < 5; i++) { printf("%d\n", vetor[i]); } } void insertionSort() { int i,chave,j; for (i = 1; i < 5;i++) { chave = vetor[i]; j = i - 1; while (vetor[j] > chave && j >= 0)
{
vetor[j + 1] = vetor[j];
j–;
}

vetor[j + 1] = chave;
}
}

void insertionSortD()
{

int chave;

atual = lista->prox;

while (atual != NULL)
{
chave = atual->inf;
anterior = atual->ant;

while(anterior != NULL && anterior->inf > chave)
{
anterior->prox->inf = anterior->inf;
anterior = anterior->ant;
}

if (anterior == NULL)
lista->inf = chave;
else
anterior->prox->inf = chave;

atual = atual->prox;
}
}

int main(int argc, char** argv)
{
add(5);
add(4);
add(3);
add(2);
add(1);

//Dinamico
insertionSortD();
listarD();

//Estático
/*
insertionSort();
listar();
*/

return (EXIT_SUCCESS);
}

[/C]

Desenvolvido por Prof. Emmanuel Silva Xavier.

One thought on “Estrutura de Dados – Ordenação de Vetor (Insertion Sort) em C

Deixe uma resposta

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *