Cleanups.
[TD_C.git] / TP_7_C / exo1-extra.c
CommitLineData
c2bc2b96
JB
1#include <stdio.h>
2#include <stdbool.h>
3
4void swap(int* v1, int* v2) {
5 int tempValue = *v1;
6 *v1 = *v2;
7 *v2 = tempValue;
8}
9
10/** Display the array on standard output. */
11void displayArray(int* array, int count) {
12 for (int tabIndex = 0; tabIndex < count; ++tabIndex) {
13 printf("array[%d] = %d\n", tabIndex, *(array++));
14 }
15}
16
17/** Swap every out-of-order cells at most once.
18 *
19 * @return true if a swap was performed, false if the whole array is ordered.
20 */
21bool sortFirst(int* array, int length) {
22 bool swappedValues = false;
23 int* cursor = array;
24
25 while (--length) {
26 if (*cursor > *(cursor + 1)) {
27 swap(cursor, cursor + 1);
28 swappedValues = true;
29 }
30
31 ++cursor;
32 }
33
34 return swappedValues;
35}
36
37void sortArray(int* array, int length) {
38 while (sortFirst(array, length));
39}
40
41/** Fill the array with user input. */
42void promptArray(int* array, int length) {
43 for (int tabIndex = 0; tabIndex < length; ++tabIndex) {
44 printf("Enter value for index %d:\n", tabIndex);
45 scanf("%d", array++);
46 }
47}
48
49int main() {
50 int arr[10];
51 promptArray(arr, 10);
52 sortArray(arr, 10);
53 displayArray(arr, 10);
54}