sortFirst(): only change the return value once, not at every iteration
[TD_C.git] / exo1 / exo1.c
CommitLineData
de32237f
JB
1#include <stdio.h>
2#include <stdbool.h>
3
b77c2eee 4//FIXME: Comment the code !!!
de32237f 5
b77c2eee 6void promptValue(int* addr) {
de32237f
JB
7 scanf("%d", addr);
8}
9
b77c2eee 10// The efficience of this swap alternative is debatable ..
de32237f
JB
11void xorSwap (int *v1, int *v2) {
12 if (v1 != v2) {
13 *v1 ^= *v2;
14 *v2 ^= *v1;
15 *v1 ^= *v2;
16 }
17}
18
19void swap(int* v1, int* v2) {
de32237f 20 if (v1 != v2) {
749142e7 21 int tmp = *v1;
de32237f
JB
22 *v1 = *v2;
23 *v2 = tmp;
24 }
25}
26
27void displayArray(int* array, int count) {
28 for (int i = 0; i < count; i++) {
b77c2eee 29 printf("Value in array at index[%d]= %d\n", i, array[i]);
de32237f
JB
30 }
31}
32
33bool sortFirst(int* array, int length) {
b77c2eee 34 bool rt = false;
9bd61970
JB
35 // This loop could probably be replaced by a while loop with conditions
36 // on the array values permutation AND the iteration value, later ...
de32237f
JB
37 for (int i = 0; i < length-1; i++) {
38 if (array[i] > array[i+1]) {
39 swap(&array[i], &array[i+1]);
b77c2eee 40 //xorSwap(&array[i], &array[i+1]);
9bd61970 41 if (!rt) { rt = true; };
de32237f
JB
42 }
43 }
b77c2eee
JB
44 return rt;
45}
46
47void sortArray(int* array, int length) {
48 bool rt;
49 do {
50 rt = sortFirst(array, length);
51 } while (rt);
52
de32237f
JB
53}
54
55int main() {
b77c2eee
JB
56 int tab_length = 10;
57 // GCC do not like variable sized array, even with the size variable properly initialized
58 int tab[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
59
60 for (int i = 0; i < tab_length; i++) {
61 printf("Enter integer value at array's index[%d]? ", i);
62 promptValue(&tab[i]);
de32237f 63 }
b77c2eee
JB
64
65 printf("\nView array content unsorted:\n");
66 displayArray(tab, tab_length);
67 sortArray(tab, tab_length);
68 printf("\nNow, sorting the array...\n");
69 printf("\nView array content sorted:\n");
70 displayArray(tab, tab_length);
de32237f
JB
71
72 return 0;
73}