From b77c2eee8228cc599196120657e503e4146be4b1 Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Tue, 14 Feb 2017 22:35:05 +0100 Subject: [PATCH] Implement exo1.c completly: MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit * Add user prompt for the array values; * Optimize sortArray() values inversion loop; * Beautify a bit the terminal output. Signed-off-by: Jérôme Benoit --- exo1/exo1.c | 39 ++++++++++++++++++++++++++++++--------- 1 file changed, 30 insertions(+), 9 deletions(-) diff --git a/exo1/exo1.c b/exo1/exo1.c index 822d73f..8b44ea4 100644 --- a/exo1/exo1.c +++ b/exo1/exo1.c @@ -1,12 +1,13 @@ #include #include +//FIXME: Comment the code !!! -void promptValue(const char* msg, int* addr) { - puts(msg); +void promptValue(int* addr) { scanf("%d", addr); } +// The efficience of this swap alternative is debatable .. void xorSwap (int *v1, int *v2) { if (v1 != v2) { *v1 ^= *v2; @@ -25,26 +26,46 @@ void swap(int* v1, int* v2) { void displayArray(int* array, int count) { for (int i = 0; i < count; i++) { - printf("Value in array index %d = %d\n", i, array[i]); + printf("Value in array at index[%d]= %d\n", i, array[i]); } } bool sortFirst(int* array, int length) { + bool rt = false; for (int i = 0; i < length-1; i++) { if (array[i] > array[i+1]) { swap(&array[i], &array[i+1]); - return true; + //xorSwap(&array[i], &array[i+1]); + rt = true; } } - return false; + return rt; +} + +void sortArray(int* array, int length) { + bool rt; + do { + rt = sortFirst(array, length); + } while (rt); + } int main() { - int array[5]; - for (int i = 0; i < 5; i++) { - promptValue("Valeur ?", &array[i]); + int tab_length = 10; + // GCC do not like variable sized array, even with the size variable properly initialized + int tab[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; + + for (int i = 0; i < tab_length; i++) { + printf("Enter integer value at array's index[%d]? ", i); + promptValue(&tab[i]); } - displayArray(array, 5); + + printf("\nView array content unsorted:\n"); + displayArray(tab, tab_length); + sortArray(tab, tab_length); + printf("\nNow, sorting the array...\n"); + printf("\nView array content sorted:\n"); + displayArray(tab, tab_length); return 0; } -- 2.34.1