b57e2ac794b94aa56b6209d46d1a23b852f724cf
[TD_C.git] / TP_7 / exo1 / exo1.c
1 #include <stdio.h>
2 #include <stdbool.h>
3
4 //FIXME: Comment the code !!!
5
6 void promptValue(int* addr) {
7 scanf("%d", addr);
8 }
9
10 // The efficiency of this swap alternative is debatable ..
11 void xorSwap (int *v1, int *v2) {
12 if (v1 != v2) {
13 *v1 ^= *v2;
14 *v2 ^= *v1;
15 *v1 ^= *v2;
16 }
17 }
18
19 void swap(int* v1, int* v2) {
20 if (v1 != v2) {
21 int tmp = *v1;
22 *v1 = *v2;
23 *v2 = tmp;
24 }
25 }
26
27 void displayArray(int* array, int count) {
28 for (int i = 0; i < count; i++) {
29 printf("Value in array at index[%d]= %d\n", i, array[i]);
30 }
31 }
32
33 bool sortFirst(int* array, int length) {
34 bool rt = false;
35 // This loop could probably be replaced by a while loop with conditions
36 // on the array values permutation AND the iteration value, later ...
37 for (int i = 0; i < length-1; i++) {
38 if (array[i] > array[i+1]) {
39 swap(&array[i], &array[i+1]);
40 //xorSwap(&array[i], &array[i+1]);
41 if (!rt) { rt = true; };
42 }
43 }
44 return rt;
45 }
46
47 void sortArray(int* array, int length) {
48 bool rt;
49 do {
50 rt = sortFirst(array, length);
51 } while (rt);
52
53 }
54
55 int main() {
56 int tab_length = 10;
57 int tab[tab_length];
58 for (int i = 0; i < tab_length; i++) {
59 tab[i] = 0;
60 }
61
62 for (int i = 0; i < tab_length; i++) {
63 printf("Enter integer value at array's index[%d]? ", i);
64 /* En langage C, une ligne doit être terminée par le caractère '\n'. Tant que */
65 /* la ligne n'est pas terminée et que le tampon associé au fichier n'est pas plein, */
66 /* les caractères transmis ne seront pas effectivement écrits mais tout simplement */
67 /* placés dans le tampon. On peut cependant forcer le vidage de ce tampon à l'aide */
68 /* de la fonction fflush. */
69 fflush(stdout);
70 promptValue(&tab[i]);
71 }
72
73 printf("\nView array content unsorted:\n");
74 displayArray(tab, tab_length);
75 sortArray(tab, tab_length);
76 printf("\nNow, sorting the array...\n");
77 printf("\nView array content sorted:\n");
78 displayArray(tab, tab_length);
79
80 return 0;
81 }