[Algorithm] Bubble Sort
This example shows that Bubble Sort
custom type in C.
Place largest number to the end of an array when it sorted.
// guess that other library is already included such as stdio.h
typedef struct
{
string name;
int scores;
} candidate;
candidate candidates[9];
int bubble_sort()
{
int sort_counter = 0;
for (int i = 0; i < 8; i++)
{
// swap large number to end of an array
if (candidates[i + 1].name != NULL && (candidates[i].scores > candidates[i + 1].scores))
{
swap(&candidates[i], &candidates[i + 1]);
sort_counter++;
}
}
// if not sorted, repeat
if (sort_counter > 0)
{
sort_counter = bubble_sort();
}
return sort_counter;
}
void swap(candidate *a, candidate *b)
{
candidate tmp = *a;
*a = *b;
*b = tmp;
}
// get the largest one with end element of an array
candidate result = candidates[9];
Comments