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