BlogsDope image BlogsDope

Sorting an array using bubble sort in Java

May 29, 2017 JAVA ARRAY SORT ALGORITHM LOOP 16783

Bubble sort is one of the simplest sorting algorithms. The two adjacent elements of an array are checked and swapped if they are in wrong order and this process is repeated until we get a sorted array. The steps of performing a bubble sort are:

  • Compare the first and the second element of the array and swap them if they are in wrong order.
  • Compare the second and the third element of the array and swap them if they are in wrong order.
  • Proceed till the last element of the array in a similar fashion.
  • Repeat all of the above steps until the array is sorted.

This will be more clear by the following visualizations.

Initial array

16 19 11 15

First iteration

16 19 11 15
16 19 11 15

SWAP

16 11 19 15
16 11 19 15

SWAP

16 11 15 19

Second iteration

16 11 15 19

SWAP

11 16 15 19
11 16 15 19

SWAP

11 15 16 19
11 15 16 19

Third iteration

11 15 16 19
11 15 16 19
11 15 16 19

No swap → Sorted → break the loop

Let’s code this up.

class Sort
{
    public static void main (String[] args)
    {
        int a[] = {16, 19, 11, 15, 10, 12, 14};
        
        for(int j = 0; j<a.length; j++)
        {
            //initially swapped is false
            boolean swapped = false;
            int i = 0;
            while(i<7-1)
            {
                //comparing the adjacent elements
                if (a[i] > a[i+1])
                {
                    //swapping
                    int temp = a[i];
                    a[i] = a[i+1];
                    a[i+1] = temp;
                    //Changing the value of swapped
                    swapped = true;
                }
                i++;
            }
            //if swapped is false then the array is sorted
            //we can stop the loop
            if (!swapped)
                break;
        }

        for(int x : a)
        {
            System.out.println(x);
        }

    }
}

In this code, we are just comparing the adjacents elements and swapping them if they are not in order.  We are repeating this process 7 times (number of elements in the array). We have also assigned a variable ‘swapped’ and making it ‘true’ if any two elements get swapped in an iteration. If no interchanging of elements happens then the array is already sorted and thus no change in the value of the ‘swapped’ happens and we can break the loop.


Liked the post?
Developer and founder of CodesDope.
Editor's Picks
0 COMMENT

Please login to view or add comment(s).