diff --git a/Sorting algorithms/BubbleSort.java b/Sorting algorithms/BubbleSort.java new file mode 100644 index 0000000..316eb35 --- /dev/null +++ b/Sorting algorithms/BubbleSort.java @@ -0,0 +1,39 @@ +/** + * Java implementation of bubble sort + * + * @author Carlos Abraham Hernandez (abraham@abranhe.com) + */ + + +public class BubbleSort { + + void bubbleSort(int arr[]){ + for (int i = 0; i < arr.length-1; i++) + for (int j = 0; j < arr.length-i-1; j++) + if (arr[j] > arr[j+1]){ + int temp = arr[j]; + arr[j] = arr[j+1]; + arr[j+1] = temp; + } + } + + // Function to print elements + void printArray(int arr[]){ + for (int i=0; i Array to be sorted, + low --> Starting index, + high --> Ending index */ + void sort(int arr[], int low, int high) + { + if (low < high) + { + /* pi is partitioning index, arr[pi] is + now at right place */ + int pi = partition(arr, low, high); + + // Recursively sort elements before + // partition and after partition + sort(arr, low, pi-1); + sort(arr, pi+1, high); + } + } + + /* A utility function to print array of size n */ + static void printArray(int arr[]) + { + int n = arr.length; + for (int i=0; i 0; gap /= 2) + { + // Do a gapped insertion sort for this gap size. + // The first gap elements a[0..gap-1] are already + // in gapped order keep adding one more element + // until the entire array is gap sorted + for (int i = gap; i < n; i += 1) + { + // add a[i] to the elements that have been gap + // sorted save a[i] in temp and make a hole at + // position i + int temp = arr[i]; + + // shift earlier gap-sorted elements up until + // the correct location for a[i] is found + int j; + for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) + arr[j] = arr[j - gap]; + + // put temp (the original a[i]) in its correct + // location + arr[j] = temp; + } + } + return 0; + } + + // Driver method + public static void main(String args[]) + { + int arr[] = {12, 34, 54, 2, 3}; + System.out.println("Array before sorting"); + printArray(arr); + + ShellSort ob = new ShellSort(); + ob.sort(arr); + + System.out.println("Array after sorting"); + printArray(arr); + } +} \ No newline at end of file