diff --git a/sorting/README.md b/sorting/README.md index e75bfe72..788b2f35 100644 --- a/sorting/README.md +++ b/sorting/README.md @@ -17,6 +17,12 @@ 2. [Insertion Sort](python/insertion-sort.py) 2. [Selection Sort](python/selection-sort.py) +### Java + +1. [Bubble Sort](java/bubble-sort.java) +2. [Insertion Sort](java/insertion-sort.java) +3. [Selection Sort](java/selection-sort.java) + ### JavaScript 1. [Bubble Sort](js/bubble-sort.js) diff --git a/sorting/java/bubble-sort.java b/sorting/java/bubble-sort.java new file mode 100644 index 00000000..a7938cf1 --- /dev/null +++ b/sorting/java/bubble-sort.java @@ -0,0 +1,36 @@ +// Java program for implementation of Bubble Sort +class BubbleSort +{ + void bubbleSort(int arr[]) + { + int n = arr.length; + 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+1] and arr[j] + int temp = arr[j]; + arr[j] = arr[j+1]; + arr[j+1] = temp; + } + } + + /* Prints the array */ + void printArray(int arr[]) + { + int n = arr.length; + for (int i=0; i= 0 && arr[j] > key) { + arr[j + 1] = arr[j]; + j = j - 1; + } + arr[j + 1] = key; + } + } + + /* A utility function to print array of size n*/ + static void printArray(int arr[]) + { + int n = arr.length; + for (int i = 0; i < n; ++i) + System.out.print(arr[i] + " "); + + System.out.println(); + } + + // Driver method + public static void main(String args[]) + { + int arr[] = { 12, 11, 13, 5, 6 }; + + InsertionSort ob = new InsertionSort(); + ob.sort(arr); + + printArray(arr); + } +} \ No newline at end of file diff --git a/sorting/java/selection-sort.java b/sorting/java/selection-sort.java new file mode 100644 index 00000000..64e19d51 --- /dev/null +++ b/sorting/java/selection-sort.java @@ -0,0 +1,43 @@ +// Java program for implementation of Selection Sort +class SelectionSort +{ + void sort(int arr[]) + { + int n = arr.length; + + // One by one move boundary of unsorted subarray + for (int i = 0; i < n-1; i++) + { + // Find the minimum element in unsorted array + int min_idx = i; + for (int j = i+1; j < n; j++) + if (arr[j] < arr[min_idx]) + min_idx = j; + + // Swap the found minimum element with the first + // element + int temp = arr[min_idx]; + arr[min_idx] = arr[i]; + arr[i] = temp; + } + } + + // Prints the array + void printArray(int arr[]) + { + int n = arr.length; + for (int i=0; i