aboutsummaryrefslogtreecommitdiff
path: root/semestre 2/informatique/tme/semaine4/24_insertion.c
blob: 4f44f90a2db3e7aaa05308ec89d1004eb14e7754 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#include <stdio.h>

int indiceInsert(int *tab, int taille, int nbEl, int el){
	if (nbEl >= taille) return -1; 
	int i = 0;
	while (i < nbEl && tab[i] <= el) {
		if (tab[i] == el) return -1;
		i++;
	}
	return i;
}

int insertElt(int el, int *tab, int taille, int *nb) {
	int ind = indiceInsert(tab, taille, *nb, el);
	if (ind == -1) return 0;
	int prev = 0;
	int set = 0;
	for (int i = ind; i < *nb+1; i++){
		if (set == 0) {
			set = 1;
			prev = tab[i];
			tab[i] = el;
		} else {
			int t = prev;
			prev = tab[i];
			tab[i] = t;
		}
	}
	(*nb)++;
	return 1;
}

int main(){
	int tab[10] = {0, 1, 3, 5};
	int taille = 10;
	int nb = 4;
	printf("%d\n\n", insertElt(-1, tab, taille, &nb));
	for (int i = 0; i < taille; i++){
		printf("%d. %d\n", i, tab[i]);
	}
}