Files
common/examples/bubblesort.cm

41 lines
975 B
Plaintext
Raw Permalink Normal View History

2026-03-14 14:14:37 -04:00
// Public domain / CC0. Use freely for any purpose. RoyR 2026
// bubblesort.cm - Bubble sort implementation
// Demonstrates: nested loops, array manipulation, comparisons
void printf(uint8 *fmt);
void bubble_sort(int32 *arr, int32 n) {
for (int32 i = 0; i < n - 1; i = i + 1) {
for (int32 j = 0; j < n - i - 1; j = j + 1) {
if (arr[j] > arr[j + 1]) {
// Swap
int32 temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
void print_array(int32 *arr, int32 n) {
for (int32 i = 0; i < n; i = i + 1) {
printf("%d ", arr[i]);
}
printf("\n");
}
int32 main(void) {
int32 numbers[10] = { 64, 34, 25, 12, 22, 11, 90, 88, 45, 50 };
int32 n = 10;
printf("Unsorted array: ");
print_array(numbers, n);
bubble_sort(numbers, n);
printf("Sorted array: ");
print_array(numbers, n);
return 0;
}