X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=TP_7_C%2Fexo1-extra.c;fp=TP_7_C%2Fexo1-extra.c;h=3d191f0ab5b66de5b3068a9d21a5ff72f515c2a4;hb=c2bc2b96a16dbea260d81c674abd5ac53687c273;hp=0000000000000000000000000000000000000000;hpb=e1b5a0c2efdaae55cb7ccb02126766c41b33afa4;p=TD_C.git diff --git a/TP_7_C/exo1-extra.c b/TP_7_C/exo1-extra.c new file mode 100644 index 0000000..3d191f0 --- /dev/null +++ b/TP_7_C/exo1-extra.c @@ -0,0 +1,54 @@ +#include +#include + +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++)); + } +} + +/** 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; + int* cursor = array; + + while (--length) { + if (*cursor > *(cursor + 1)) { + swap(cursor, cursor + 1); + swappedValues = true; + } + + ++cursor; + } + + return swappedValues; +} + +void sortArray(int* array, int length) { + while (sortFirst(array, length)); +} + +/** 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++); + } +} + +int main() { + int arr[10]; + promptArray(arr, 10); + sortArray(arr, 10); + displayArray(arr, 10); +}