Commit | Line | Data |
---|---|---|
c2bc2b96 JB |
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++)); | |
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 | */ | |
21 | bool 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 | ||
37 | void sortArray(int* array, int length) { | |
38 | while (sortFirst(array, length)); | |
39 | } | |
40 | ||
41 | /** Fill the array with user input. */ | |
42 | void 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 | ||
49 | int main() { | |
50 | int arr[10]; | |
51 | promptArray(arr, 10); | |
52 | sortArray(arr, 10); | |
53 | displayArray(arr, 10); | |
54 | } |