diff --git a/README.md b/README.md index d2120887..9af71646 100644 --- a/README.md +++ b/README.md @@ -19,7 +19,7 @@ This repository contains examples of various algorithms written on different pro | [Counting Sort](https://en.wikipedia.org/wiki/Counting_sort) |[:octocat:](counting_sort/C) | [:octocat:](counting_sort/Cpp) | | [:octocat:](counting_sort/Python) | | [Radix Sort](https://en.wikipedia.org/wiki/Radix_sort) | | [:octocat:](radix_sort/Cpp) | | [:octocat:](radix_sort/Python) | | [Binary Search](https://en.wikipedia.org/wiki/Binary_search_algorithm) | | [:octocat:](binary_search/Cpp) | | [:octocat:](binary_search/Python) | -| [Bubble Sort](https://en.wikipedia.org/wiki/Bubble_sort) | [:octocat:](bubble_sort/C) | [:octocat:](bubble_sort/Cpp) | | | +| [Bubble Sort](https://en.wikipedia.org/wiki/Bubble_sort) | [:octocat:](bubble_sort/C) | [:octocat:](bubble_sort/Cpp) | [:octocat:](bubble_sort/Java) | | | [Shell Sort](https://en.wikipedia.org/wiki/Shellsort) | [:octocat:](shell_sort/C) | | | [:octocat:](shell_sort/Python) | | [Heap Sort](https://en.wikipedia.org/wiki/Heapsort) | | | | [:octocat:](heap_sort/python) | | [Maximum Subarray Problem](https://en.wikipedia.org/wiki/Maximum_subarray_problem) | | | | [:octocat:](/maximum_subarray/Python)| diff --git a/bubble_sort/Java/bubble_sort.java b/bubble_sort/Java/bubble_sort.java new file mode 100644 index 00000000..6a0ca373 --- /dev/null +++ b/bubble_sort/Java/bubble_sort.java @@ -0,0 +1,40 @@ +public class bubble_sort { + public static void main(String[] args){ + //Taking a sample array for sorting it. + int[] nums = {12, 45, 23, 78, 67}; + + //calling the method and passing the array in it. + bubble(nums, nums.length); + //Printing the sorted array + print_sorted_array(nums); + } + //The recurisve method that takes in the array and the length of it. + public static void bubble(int[] nums, int end){ + //base case + if (end == 1) { + return; + } + //for loop that iterates and sorts the sorts the array + for (int i = 0; i < end - 1; i++) { + if (nums[i] > nums[i + 1]) { + int temp = nums[i]; + nums[i] = nums[i + 1]; + nums[i + 1] = temp; + } + } + //calling the method again to sort the rest of the elements on next iteration + bubble(nums, end - 1); + } + + //Method to print an array + public static void print_sorted_array(int arr[]) { + + //storing the length of an array using the .length function in Java + int n = arr.length; + //For loop that iterates over each element of the array and then prints it. + for (int i = 0; i < n; ++i) + System.out.print(arr[i] + " "); + System.out.println(); + } + +}