|
| 1 | +package com.rampatra.arrays.sorting; |
| 2 | + |
| 3 | +import java.util.Arrays; |
| 4 | + |
| 5 | +/** |
| 6 | + * @author rpatra16 |
| 7 | + * @since 03/11/2018 |
| 8 | + */ |
| 9 | +public class BubbleSort { |
| 10 | + |
| 11 | + /** |
| 12 | + * In bubble sort, we start at the beginning of the array and swap |
| 13 | + * the first two elements if the first is greater than the second. |
| 14 | + * Then, we go to the next pair, and so on, continuously making sweeps |
| 15 | + * of the array until it is sorted. In doing so, the smaller items |
| 16 | + * slowly "bubble" up to the beginning of the list and in each inner |
| 17 | + * iteration the largest element is sorted. Ergo, the inner loop runs |
| 18 | + * until {@code length - i - 1} times. To learn more: |
| 19 | + * {@see https://youtu.be/6Gv8vg0kcHc} |
| 20 | + * |
| 21 | + * @param ar |
| 22 | + */ |
| 23 | + private static void bubbleSort(int[] ar) { |
| 24 | + for (int i = 0; i < ar.length - 1; i++) { |
| 25 | + for (int j = 0; j < ar.length - i - 1; j++) { |
| 26 | + if (ar[j] > ar[j + 1]) { |
| 27 | + swap(ar, j, j + 1); |
| 28 | + } |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + private static void swap(int[] ar, int i, int j) { |
| 34 | + int temp = ar[i]; |
| 35 | + ar[i] = ar[j]; |
| 36 | + ar[j] = temp; |
| 37 | + } |
| 38 | + |
| 39 | + public static void main(String[] args) { |
| 40 | + int[] ar = {2, 5, 1, 7, 8}; |
| 41 | + System.out.println(Arrays.toString(ar)); |
| 42 | + bubbleSort(ar); |
| 43 | + System.out.println(Arrays.toString(ar)); |
| 44 | + ar = new int[]{7, 5, 1, 7, 8, 0, 23}; |
| 45 | + System.out.println(Arrays.toString(ar)); |
| 46 | + bubbleSort(ar); |
| 47 | + System.out.println(Arrays.toString(ar)); |
| 48 | + } |
| 49 | +} |
0 commit comments