From f40566906deef95b21af813f9b4eb35cf73d5ae8 Mon Sep 17 00:00:00 2001 From: Farheen Shabbir Shaikh Date: Sun, 8 Jun 2025 17:59:27 -0700 Subject: [PATCH] Add Bubble Sort algorithm with comments --- Sorting/BubbleSort.java | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 Sorting/BubbleSort.java diff --git a/Sorting/BubbleSort.java b/Sorting/BubbleSort.java new file mode 100644 index 000000000000..511c8dc6d653 --- /dev/null +++ b/Sorting/BubbleSort.java @@ -0,0 +1,40 @@ +/** + * BubbleSort.java + * This program implements the Bubble Sort algorithm. + * Time Complexity: O(n^2) + */ + +public class BubbleSort { + + public static void bubbleSort(int[] arr) { + int n = arr.length; + boolean swapped; + for (int i = 0; i < n - 1; i++) { + swapped = false; + + 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; + + swapped = true; + } + } + + // If no two elements were swapped, array is sorted + if (!swapped) + break; + } + } + + public static void main(String[] args) { + int[] arr = {64, 25, 12, 22, 11}; + bubbleSort(arr); + System.out.println("Sorted array:"); + for (int num : arr) { + System.out.print(num + " "); + } + } +} \ No newline at end of file