next up previous contents
suivant: Transformée de Fourier monter: Corrigés des programmes précédent: Tri fusion   Table des matières

Tri par insertion

triInsertion.c


#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include"linkedList.h"

link* insert(link* list, link* item, int (*estInf)(void*, void*))
{
  if (list == NULL)
    {
      item->next = NULL;
      return item;
    }
  if (estInf(item->data, list->data))
    {
      item->next = list;
      return item;
    }
  list->next = insert(list->next, item, estInf);
  return list;
}

link* triInsertion(link* list, int (*estInf)(void*, void*))
{
  if (list == NULL)
    return NULL;
  return insert(triInsertion(list->next, estInf), list, estInf); 
}

void linkedListSort(linkedList* l, int (*estInf)(void*, void*))
{
  l->first = triInsertion(l->first, estInf);
  void setLast(link* ll)
    {
      if (ll == NULL)
	l->last = NULL;
      else
	if (ll->next == NULL)
	  l->last = ll;
	else	  
	  setLast(ll->next);
    }
  setLast(l->first);
}

int estInf(void* i, void* j)
{
  return (*(int*)i <= *(int*)j  ) ? 1 : 0;
}

void destroyInt(void* i)
{
  free((int*)i);
}

int main()
{
  int i = 1;
  int* k;
  linkedList* l = linkedListCreate();
  for(i = 100 ; i > 0 ; i--) 
    {
      k = (int*)malloc(sizeof(int));
      *k = i;
      linkedListAppend(l, k);
    }
  void printInt(void* i)
    {
      printf("%d ", *((int*)i));
    }
  linkedListApply(l, printInt);
  printf("\n");
  linkedListSort(l, estInf);
  linkedListApply(l, printInt);
  printf("\n");
  linkedListDestroy(l, destroyInt);
  return 0;
}



klaus 2010-08-05