Add TP 7 correction.
[TD_C.git] / TP_7_C / exo1-full.c
diff --git a/TP_7_C/exo1-full.c b/TP_7_C/exo1-full.c
new file mode 100644 (file)
index 0000000..451816b
--- /dev/null
@@ -0,0 +1,55 @@
+#include <stdio.h>
+#include <stdbool.h>
+
+void swap(int* v1, int* v2) {
+    int tempValue = *v1;
+    *v1 = *v2;
+    *v2 = tempValue;
+}
+
+/** Display the array on standard output. */
+void displayArray(int* array, int count) {
+    for (int tabIndex = 0; tabIndex < count; ++tabIndex) {
+        printf("array[%d] = %d\n", tabIndex, array[tabIndex]);
+    }
+}
+
+/** Swap every out-of-order cells at most once.
+ *
+ * @return true if a swap was performed, false if the whole array is ordered.
+ */
+bool sortFirst(int* array, int length) {
+    bool swappedValues = false;
+
+    for (int tabIndex = 0; tabIndex < (length - 1); ++tabIndex) {
+        if (array[tabIndex] > array[tabIndex + 1]) {
+            swap(&array[tabIndex], &array[tabIndex + 1]);
+            swappedValues = true;
+        }
+    }
+
+    return swappedValues;
+}
+
+void sortArray(int* array, int length) {
+    bool swappedValues;
+
+    do {
+        swappedValues = sortFirst(array, length);
+    } while (swappedValues);
+}
+
+/** Fill the array with user input. */
+void promptArray(int* array, int length) {
+    for (int tabIndex = 0; tabIndex < length; ++tabIndex) {
+        printf("Enter value for index %d:\n", tabIndex);
+        scanf("%d", &array[tabIndex]);
+    }
+}
+
+int main() {
+    int arr[10];
+    promptArray(arr, 10);
+    sortArray(arr, 10);
+    displayArray(arr, 10);
+}