APS105 Textbook 14.3 - Bubble Sort

What is Bubble Sort?

Bubble sort is a method in which you iterate through an array and compare the values at two adjacent indices, swapping them if they are in the wrong order. You repeat this until the whole array is sorted.

Example: Sort Array from Lowest to Highest

Sort an array with 4 integers from highest to lowest.

#include <stdio.h>
#include <stdbool.h>
#define ARRAY_SIZE 4
int main(void) {
	int arr[ARRAY_SIZE] = {2, 5, 3, 1};
	bool sorted = false;
	int iteration = 0;
	while (!sorted) {
		bool iterationSorted = true;
		for (int i = 0; i < ARRAY_SIZE - 1; ++i) {
			if (arr[i] > arr[i + 1]) {
				int tmp = arr[i + 1];
				arr[i + 1] = arr[i];
				arr[i] = tmp;
				iterationSorted = false;
			}
		}
		if (iterationSorted) {
			sorted = true;
			for (int i = 0; i < ARRAY_SIZE; ++i) {
				printf("%d ", arr[i]);
			}
		} else {
			++iteration;
			printf("After iteration %d: ", iteration);
			for (int i = 0; i < ARRAY_SIZE; ++i) {
				printf("%d ", arr[i]);
			}
			printf("\n");
		}
	}
}