,

Sorting in Java – Bubble Sorting Algorithm

Today, I’ll be discussing Bubble sorting in Java. It’s another sorting technique. In my previous video, you must have seen about the binary search and the linear search, how they work, two different sorting techniques. Today, I’ll be telling you how a bubble sort works. I’ll start with the very basics, how it actually works in the background, and how it gives you the output. Then we’ll move on to the coding part.

Let’s take an array. Bubble sorting is basically applied to an array, like a set of data you have taken in the form of an array. I’ll take a small example. Let’s say my array elements are 12, 10, 30, 10.

public class BubbleSort {

public static void main(String[] args) {
    int[] arr = {12, 1, 30, 10};
    bubbleSort(arr);
    System.out.println("Array after sorting:");
    for (int i = 0; i < arr.length; i++) {
        System.out.print(arr[i] + " ");
    }
}

public static void bubbleSort(int[] arr) {
    int n = arr.length;
    int temp;

    for (int i = 0; i <= n; i++) {
        for (int j = 1; j < n - i; j++) {
            if (arr[j - 1] > arr[j]) {
                temp = arr[j - 1];
                arr[j - 1] = arr[j];
                arr[j] = temp;
            }
        }
    }
}

}

These are my array elements. What happens in Bubble sorting is that it keeps on checking your array. It will sort your array into an ascending order. If you see over here, it’s randomly placed elements inside an array. So, it will keep on sorting the elements, unless and until it gets me an ascending order element.

So, how does it actually work? It compares and swaps. It compares and swaps. Ascending order means smaller to bigger. In an array, remove these. So now, the array we have, we’ll start with the element which is 3 inside the array and then 10. We’ll compare these two elements and check whether 3 is greater than 10 or not. If yes, it is greater than 10, then it will swap the position. The position will be swapped.

The main thing is, we are working on bubble sorting in which the outcome of the array should be an ascending order array. That means our outcome should be something like this for this particular array. If I create another array, the sorted elements would be something like 0, 1, 3, 10, and then 20. This would be my bubble-sorted array of this array.

So, that’s how bubble sorting works in Java. It compares and swaps elements in the array until it achieves an ascending order. If you have any questions or want more explanations, feel free to ask!


Author

Sona Avatar

Written by

Leave a Reply

Trending

CodeMagnet

Your Magnetic Resource, For Coding Brilliance

Programming Languages

Web Development

Data Science and Visualization

Career Section

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4205364944170772"
     crossorigin="anonymous"></script>