Showing posts with label Sorting. Show all posts
Showing posts with label Sorting. Show all posts

Sunday, 28 July 2024

Bubble Sorting in Java

Bubble sort is a sorting algorithm that works by repeatedly iterating through the array comparing each pair of adjoining elements and swapping them if they are in the wrong order.

Let us understand how Bubble sorting works with diagrammatic representation:

Say for example, if we have array elements as shown below:

65, 47, 70, 9

Pass 1:

To begin with, the element at 0th and 1st index are compared. Their positions are swapped, if element at 0th index is greater than element at 1st index.

Since, 65 is greater than 47, swap occurs.

Now, elements at 1st and 2nd index are compared.
Since, 65 is less than 70, no swap required.

Now, elements at 2nd and 3rd index are compared.

Since, 70 is greater than 9, swap occurs and now, the list will look like this.

In the next pass, the second highest number is placed in the second last position and so on.  This process will keep on repeating until the entire array is sorted.

Below program will teach you how to sort the numbers in an array using Bubble Sorting.

class BubbleSort
{
    public static void main(String[]args)
    {
        int list[] = {65,47,40,9,37,72,45,17};
        int len = list.length;
        for(int i = 0;i<len-1;i++)
        {
            for(int j = 0;j<len-i-1;j++)
            {
                if(list[j]>list[j+1])
                {
                    //swapping of adjacent elements done here
                    int tmp = list[j];
                    list[j] = list[j+1];
                    list[j+1] = tmp;
                }
            }
        }
        System.out.println("Sorted array is");
        for(int i = 0;i<len-1;i++)
        {
            System.out.println(list[i]);
        }
    }
}

Demonstration:

1. A class namely BubbleSort have been defined.
2. A main method have been defined.
3. An array namely list of int data type has been declared and unsorted elements are stored in it.
4. Stores the length of list in len variable.
5. The outer loop iterates through the entire array.

6. Inner loop iterates through the remaining unsorted array only. It is done by subtracting the value of counter variable i in inner loop test condition (len-i-1).
7. Compares two adjacent elements, i.e. element at jth position and that as (j+1)th position.
8. Stores the value of the current element in a temporary variable.
9. Stores the value of the next element of the array in the current element.
10. Stores the value of the temporary variable in the next element