| 1 | #include <stdio.h> |
| 2 | #include <stdbool.h> |
| 3 | |
| 4 | void swap(int* v1, int* v2) { |
| 5 | int tempValue = *v1; |
| 6 | *v1 = *v2; |
| 7 | *v2 = tempValue; |
| 8 | } |
| 9 | |
| 10 | /** Display the array on standard output. */ |
| 11 | void displayArray(int* array, int count) { |
| 12 | for (int tabIndex = 0; tabIndex < count; ++tabIndex) { |
| 13 | printf("array[%d] = %d\n", tabIndex, array[tabIndex]); |
| 14 | } |
| 15 | } |
| 16 | |
| 17 | /** Perform one swap on the first two values not in increasing order. |
| 18 | * |
| 19 | * @return true if a swap was performed, false if the whole array is ordered. |
| 20 | */ |
| 21 | bool sortFirst(int* array, int length) { |
| 22 | for (int tabIndex = 0; tabIndex < (length - 1); ++tabIndex) { |
| 23 | if (array[tabIndex] > array[tabIndex + 1]) { |
| 24 | swap(&array[tabIndex], &array[tabIndex + 1]); |
| 25 | return true; |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | return false; |
| 30 | } |
| 31 | |
| 32 | void sortArray(int* array, int length) { |
| 33 | bool swappedValues; |
| 34 | |
| 35 | do { |
| 36 | swappedValues = sortFirst(array, length); |
| 37 | } while (swappedValues); |
| 38 | } |
| 39 | |
| 40 | int main() { |
| 41 | int arr[10] = {23, 2, 0, 4, 56, 3, 7, 8, 98, 1}; |
| 42 | sortArray(arr, 10); |
| 43 | displayArray(arr, 10); |
| 44 | } |