Java Example – Bubble Sort Algorithm




Java Tutorial for Beginners
Java Tutorial for Beginners

The bubble sort Algorithm simply compares adjacent elements and exchanges them if they are out of order.

To apply the Bubble Sort we follow the following steps.

  • Compare 1st two elements and exchange them if they are out of order.
  • Move down one element and compare 2nd and 3rd elements. Exchange if necessary. Continue until end of array.
  • Pass through array again, repeating process and exchanging as necessary.
  • Repeat until a pass is made with no exchanges.

In this lesson we will learn how to write a source code in Java  programming language for doing simple bubble sort using array in ascending order.

How to Implement Bubble Sort Algorithm in Java

public class BubbleSort {
    public static void main(String[] args)
    {
        int[] c={154,58,5,542,5,84,96,35,954,269,516,169,503,85,695,415,492};//
        System.out.print("Before Bubble sort \n");
        printA(c);
        bubble(c);
        System.out.print("\nAfter Bubble sort \n");
        printA(c);
    }
    public static void printA(int[] a)
    {
        for(int i=0 ; i< a.length; i++)
        {
            System.out.print(a[i]+"  ");
        }
    }
    public static void bubble(int[] a)
    {
        int temp = 0;
        for(int i =a.length;i>=0; i--)
        {
            for(int j=0;j< i-1;j++)
            {
                if(a[j]>a[j+1])
                {
                    temp = a[j+1];
                    a[j+1] = a[j];
                    a[j] = temp;
                }
            }

        }

    }
}

/**
 * Output
 Before Bubble sort
 154  58  5  542  5  84  96  35  954  269  516  169  503  85  695  415  492
 After Bubble sort
 5  5  35  58  84  85  96  154  169  269  415  492  503  516  542  695  954
 */

 

 





Partner Sites

VideoToGifs.com

EasyOnlineConverter.com

SqliteTutorials.com





Be the first to comment

Leave a Reply

Your email address will not be published.


*