Saturday 30 July 2016

Bubble Sort

bubble sort
import java.io.*;
class Bubblesort
{
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n=0,i,j,t;
int a[]=new int[10];
System.out.println("Enter size of the array:");
try
{
n=Integer.parseInt(br.readLine());
}
catch(Exception e) {}
System.out.println("Enter elements into the array:");
try
{
for(i=0;i<n;i++)
a[i]=Integer.parseInt(br.readLine());
}
catch(Exception e) {}
for(i=0;i<n-1;i++)
for(j=0;j<n-1-i;j++)
if(a[j]>a[j+1])
{
t=a[j];
a[j]=a[j+1];
a[j+1]=t;
}
System.out.println("The sorted array is:");
for(i=0;i<n;i++)
System.out.println(a[i]);
}
}
Output:
javac Bubblesort.java
java Bubblesort
Enter the size of array
5
Enter the elements into the array
45
34
76
12
69
The sorted array is
12 34 45 69 76