33 if (
entries != NULL && sortIndices != NULL && sortStrategy != NULL)
35 for (
size_t leftIndex = 0; leftIndex < numEntries - 1; leftIndex++)
37 for (
size_t rightIndex = leftIndex + 1; rightIndex < numEntries; rightIndex++)
42 swapEntries = !swapEntries;
46 int tempIndex = sortIndices[leftIndex];
47 sortIndices[leftIndex] = sortIndices[rightIndex];
48 sortIndices[rightIndex] = tempIndex;
70 if (
entries != NULL && sortIndices != NULL)
73 printf(
" Sort strategy: %s (order = %s)\n", sortStrategy->
name, sortStrategy->
reversedSort ?
"Descending" :
"Ascending");
74 printf(
" %-6s %3s %3s\n",
"Name",
"Age",
"Height");
75 printf(
" %6s %3s %3s\n",
"------",
"---",
"------");
76 for (
size_t index = 0; index < numEntries; index++)
79 printf(
" %-6s %3d %3d\"\n", entry->
Name, entry->
Age, entry->
Height);
123 printf(
"\nStrategy Exercise\n");
126 int* sortIndices = malloc(numEntries *
sizeof(
int));
127 if (sortIndices != NULL)
129 for (
int index = 0; index < (int)numEntries; index++)
131 sortIndices[index] = index;
152 printf(
" Error! Out of memory creating array of indices to sort on!\n");
static EntryInformation entries[]
List of individuals to play around with in the Strategy exercise.
static void Display_Entries(const EntryInformation *entries, size_t numEntries, int *sortIndices, SortStrategy *sortStrategy)
Display the list of EntryInformation objects that have (presumably) been sorted with the given SortSt...
static void Sort_Entries(const EntryInformation *entries, size_t numEntries, int *sortIndices, SortStrategy *sortStrategy)
Sort the list of EntryInformation objects using the sorting strategy given in the SortStrategy object...
void Strategy_Exercise(void)
Example of using the Strategy Pattern.
void SortStrategy_Initialize(SortStrategy *strategy, SortOptions sortOption, bool reversedSort)
Initialize a SortStrategy object with the desired strategy.
Declaration of the SortStrategy structure and the SortStrategy_Initialize() function as used in the S...
@ Sort_ByAge
Sort numerically by age in ascending order.
@ Sort_ByHeight
Sort numerically by height in ascending order.
@ Sort_ByName
Sort alphabetically name in ascending order.
Declaration of the Strategy_Exercise() function as used in the Strategy Pattern.
Represents an individual with a Name, Age, and Height.
int Age
Age of this individual, in years.
const char * Name
Name of this individual.
int Height
Height of this individual, in inches.
Represents the strategy to use for sorting EntryInformation objects.
bool reversedSort
True if to reverse the order of the sort.
const char * name
Name of the strategy (for display purposes)
CompareFunction compareFunction
Compare function that determines the order of two entries.