Last active
August 20, 2021 00:41
-
-
Save BrandonIrizarry/9c234a5dc03f60050f2f740fd5e3e1ba to your computer and use it in GitHub Desktop.
A minimal example of bubble sort, using a character array as an example. (C language practice.)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Brandon C. Irizarry | |
8/19/21 | |
Example of Bubble Sort (ascending order). | |
Upon studying this a bit further, I missed out on | |
an invariant of the sort. | |
(The array is always scanned from the beginning each time.) | |
Should compile as ISO C90. | |
*/ | |
#include <stdio.h> | |
typedef enum { FALSE, TRUE } bool; | |
/* Bubble sort involves performing swaps. */ | |
void swap (char *a, char *b) { | |
int temp = *a; | |
*a = *b; | |
*b = temp; | |
} | |
/* When I heard the description, having a separate function for the | |
pass step seemed most natural. */ | |
bool run (char array[], size_t n) { | |
int i; | |
bool sorted = TRUE; | |
for (i = 0; i < n - 1; i++) { | |
if (array[i] > array[i + 1]) { | |
swap(&array[i], &array[i + 1]); | |
sorted = FALSE; | |
} | |
} | |
return sorted; | |
} | |
int main (void) { | |
bool sorted = FALSE; | |
char name[] = "Brandon"; | |
/* Print my name. */ | |
printf("%s\n", name); | |
/* The actual bubble-sort procedure. Note that we're only sorting up | |
to but not including the null-byte. */ | |
do { | |
sorted = run(name, (sizeof name) - 1); | |
} while (!sorted); | |
/* Reprint my name, to demonstrate the sorting effect. */ | |
printf("%s\n", name); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment