Bubble Sort program in Java

Bubble sort:

It is one of the simplest sorting algorithm.In bubble sort each and every element is compared with its adjacent element and swap if at wrong place diagram below shows the working of bubble sort.

Bubble Sort in Java


Bubble Sort in Java

 

import java.io.*;
class bubble_sort
{
public static void main(String args[ ])throws IOException
{
int i,n=0;
DataInputStream in = new DataInputStream(System.in);
System.out.print("Enter how many numbers to be sorted : ");
n = Integer.parseInt(in.readLine());
int a[]=new int[n];

System.out.println("Enter numbers");
for(i=0;i<n;i++)
a[i]= Integer.parseInt(in.readLine());
System.out.println();

System.out.println("SORTING BY BUBBLE SORT");
int hold,j,pass;
for(pass=0;pass<n-1;pass++)
{
for(j=0;j<n-1;j++)
{
if(a[j]>a[j+1])
{
hold=a[j];
a[j]=a[j+1];
a[j+1]=hold;
}
}
}
System.out.println("\nSorted Elements are :");
for(i=0;i<n;i++)
System.out.print("\t"+a[i]);
System.out.println();
}
}

To reduce the number of comparisons in use following bubble sort logic

int hold,j,pass;
for(pass=0;pass<n-1;pass++)
{
for(j=0;j<n-pass-1;j++)                               //to avoid needless comparisons
{
if(a[j]>a[j+1])
{
hold=a[j];
a[j]=a[j+1];
a[j+1]=hold;
}
}
}

/*Bubble Sort in Java Output:

Enter how many numbers to be sorted : 5
Enter numbers
10
4
5
7
2

SORTING BY BUBBLE SORT

Sorted Elements are :
2  4  5  7  10

*/

Bubble Sort in Java

Bubble Sort in Java

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *