Bubble Sort



	#include <stdio.h>
	#include <stdlib.h>

	// Function Prototypes
	void bubbleSort(int *arr, int len);
	void swap(int *arr, int a, int b);

	void bubbleSort(int *arr, int len) {
		int i, j, flag;
		for (i = 0; i < len; i++) {
			flag = 0;
			for (j = 1; j < len - i; j++) {
				if (arr[j - 1] > arr[j]) {
					swap(arr, j - 1, j);
					flag = 1;
				}
			}
			if (!flag)
				break;
		}
	}

	void swap(int *arr, int a, int b) {
		int temp = arr[a];
		arr[a] = arr[b];
		arr[b] = temp;
	}

	void printArr(int *arr, int len) {
		for (int i = 0; i < len; i++)
			printf("%d ", arr[i]);
		printf("\n\n");
	}

	int main(void) {
		int len = 20;
		int *arr = malloc(len * sizeof(int));
		for (int i = 0; i < len; i++) {
			arr[i] = rand() % 100;
		}
		printf("Printing Array...\n\n");
		printArr(arr, len);
		printf("Applying Bubble Sort...\n\n");
		bubbleSort(arr, len);
		printf("Printing Sorted Array...\n\n");
		printArr(arr, len);
		free(arr);
		return 0;
	}
						
						

Academic Notice: The code shown here is provided solely as a learning reference. Copying and pasting is intentionally disabled to encourage independent practice. Students should implement solutions on their own to demonstrate understanding. This material is not intended for direct submission in assignments.

Additionally: This code was written by a former CS1 student and may not reflect your professor’s intended solution or instructional approach. For coursework, students are expected to follow examples, conventions, and requirements presented in class and in professor-assigned materials.