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[tabIndex]); | |
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 | ||
24 | for (int tabIndex = 0; tabIndex < (length - 1); ++tabIndex) { | |
25 | if (array[tabIndex] > array[tabIndex + 1]) { | |
26 | swap(&array[tabIndex], &array[tabIndex + 1]); | |
27 | swappedValues = true; | |
28 | } | |
29 | } | |
30 | ||
31 | return swappedValues; | |
32 | } | |
33 | ||
34 | void sortArray(int* array, int length) { | |
35 | bool swappedValues; | |
36 | ||
37 | do { | |
38 | swappedValues = sortFirst(array, length); | |
39 | } while (swappedValues); | |
40 | } | |
41 | ||
42 | /** Fill the array with user input. */ | |
43 | void promptArray(int* array, int length) { | |
44 | for (int tabIndex = 0; tabIndex < length; ++tabIndex) { | |
45 | printf("Enter value for index %d:\n", tabIndex); | |
46 | scanf("%d", &array[tabIndex]); | |
47 | } | |
48 | } | |
49 | ||
50 | int main() { | |
51 | int arr[10]; | |
52 | promptArray(arr, 10); | |
53 | sortArray(arr, 10); | |
54 | displayArray(arr, 10); | |
55 | } |