Skip to content

Instantly share code, notes, and snippets.

@realFranco
Created January 17, 2020 14:59
Show Gist options
  • Save realFranco/b381333f8db5ce93b4790372fdec5d35 to your computer and use it in GitHub Desktop.
Save realFranco/b381333f8db5ce93b4790372fdec5d35 to your computer and use it in GitHub Desktop.
Insertion Sort - Implelemented using Linked Lists.
/*
* insercion.l.c
* franco Gil
* date: 23*3*17
* Insertion sort algorithm, using dynamic memory, and
* self NODES for construct a simple linked LIST.
*/
#include <stdio.h>
#include <stdlib.h>
typedef struct NODE_
{
int data;
struct NODE_ *next;
}node;
typedef struct
{
int size;
node *head;
node *last;
}list;
void insercion_l(list *l);
list *create();
void insert_at_final(list *l, int newcommer);
void gen_congruencial(list * l, int k);
void print_l(list *l);
int main()
{
list *l;
int N;
do{
l = create();
printf("Size of the list N=:");
scanf("%d", &N);
gen_congruencial(l, N);
print_l(l); insercion_l(l); print_l(l);
free(l);
}while(N < 28);
return 0;
}
void insercion_l(list *l) // start the game
{
node *i, *j, *aj, *temp, *at;
int band = 0;
i = l->head;
j = i->next; aj = i;
temp = i; at = NULL;
while(aj && j)
{
while(j && (aj->data > j->data))
{
aj->next = j->next;
if(j->data <= i->data) // j < head
{
j->next = l->head;
l->head = j;
j->next = i;
}
//j->next = i;
while((j->data > temp->data)/*&& (aj && j)*/)
{
at = temp;
j->next = at;
temp = temp->next;
band = 1;
}
if(band)
{
at->next = j;
j->next = temp;
}
j = aj->next;
i = l->head;
temp = i;
band = 0;
}
if(aj->next)
{
aj = j;
j = j->next;
}
}
if(!i) // i == NULL
printf("empty list\n"); //warnings(2);
}
list *create()
{
list *l;
l = (list *)malloc(sizeof(list));
l->size = 0;
l->head = NULL;
l->last = NULL;
return l;
}
void insert_at_final(list *l, int newcommer)
{
node *aux;
node *temp;
temp = (node *)malloc(sizeof(node));
temp->data = newcommer;
temp->next = NULL;
if(!l->size)
{
l->head = temp;
l->last = temp;
l->size = 1;
}
else
{
aux = l->last;
aux->next = temp;
l->last = temp;
l->size++;
temp->next = NULL;
}
aux = NULL; temp = NULL;
}
// Create random numbers on every code execution
void gen_congruencial(list * l, int k)
{
int a = 7, x = 5, c = 1, m = 26;
int j, aux = 0;
for(j = 0; j < k; j++)
{
x = a*x + c; aux = x % m;
insert_at_final(l, aux);
}
}
void print_l(list *l)
{
node *aux;
int i = 0, k = l->size;
aux = l->head;
while(k--)
{
if(aux->data < 0)
printf("(%d)", aux->data);
else
printf("%d", aux->data);
if(i++ < l->size-1)
printf("->");
aux = aux->next;
}
printf("||\n");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment