From 0f48885c90416f322d4482acfe7c9fbf714134b2 Mon Sep 17 00:00:00 2001 From: Aryan-Bhendarkar Date: Tue, 29 Oct 2024 17:58:36 +0530 Subject: [PATCH] Create bubblesort.c --- C/bubblesort.c | 36 ++++++++++++++++++++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 C/bubblesort.c diff --git a/C/bubblesort.c b/C/bubblesort.c new file mode 100644 index 0000000..acace77 --- /dev/null +++ b/C/bubblesort.c @@ -0,0 +1,36 @@ +#include + +void bubbleSort(int arr[], int n) { + for (int i = 0; i < n - 1; i++) { + for (int j = 0; j < n - i - 1; j++) { + if (arr[j] > arr[j + 1]) { + // Swap arr[j] and arr[j + 1] + int temp = arr[j]; + arr[j] = arr[j + 1]; + arr[j + 1] = temp; + } + } + } +} + +void printArray(int arr[], int n) { + for (int i = 0; i < n; i++) { + printf("%d ", arr[i]); + } + printf("\n"); +} + +int main() { + int arr[] = {5, 1, 4, 2, 8}; + int n = sizeof(arr) / sizeof(arr[0]); + + printf("Original array:\n"); + printArray(arr, n); + + bubbleSort(arr, n); + + printf("Sorted array:\n"); + printArray(arr, n); + + return 0; +}