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 diff --git a/Sorting/InsertionSort.java b/Sorting/InsertionSort.java new file mode 100644 index 000000000000..8da2ba4c5331 --- /dev/null +++ b/Sorting/InsertionSort.java @@ -0,0 +1,33 @@ +/** + * InsertionSort.java + * This program implements the Insertion Sort algorithm. + * Time Complexity: O(n^2) in worst case, O(n) in best case (already sorted). + */ + +public class InsertionSort { + + public static void insertionSort(int[] arr) { + // Loop from the second element to the end + for (int i = 1; i < arr.length; i++) { + int key = arr[i]; // Store the current element to be inserted + int j = i - 1; + + // Move elements of arr[0..i-1], that are greater than key, + // to one position ahead of their current position + while (j >= 0 && arr[j] > key) { + arr[j + 1] = arr[j]; // Shift element to the right + j = j - 1; + } + arr[j + 1] = key; // Insert the key into its correct position + } + } + + public static void main(String[] args) { + int[] arr = {29, 10, 14, 37, 13}; + insertionSort(arr); + System.out.println("Sorted array:"); + for (int num : arr) { + System.out.print(num + " "); + } + } +} \ No newline at end of file