Bubble sort in Java
First Version
import java.util.*;
public class BubbleSort
{
public static void main(String args[])
{
int n[]=new int[5];
int i, j, t;
Scanner sc=new Scanner(System.in);
System.out.println("Enter Elements in Array");
for(i=0; i<5; i++)
{
n[i]=sc.nextInt();
}
System.out.println("Before Sorted Order");
for(i=0;i<5;i++)
{
System.out.print(n[i] + " ");
}
System.out.println();
for(i=0;i<4;i++)
{
for(j=0;j<4-i;j++)
{
if(n[j]>n[j+1])
{
t=n[j];
n[j]=n[j+1];
n[j+1]=t;
}
}
}
System.out.println("Sorted Order");
for(i=0;i<5;i++)
{
System.out.print(n[i] + " ");
}
}
}
Process defines pictorially
second version
public class BubbleSortProject
{
int n[]={8,18,20,6,1,4,19,16,15,3};
int l,i,j,t;
void Process()
{
l=n.length;
for(i=0;i<l;i++)
{
System.out.print(n[i]+" ");
}
System.out.println();
}
void BubbleSort()
{
l=n.length;
for(i=0;i<l-1;i++)
{
for(j=0;j<(l-1)-i;j++)
{
if(n[j]<n[j+1])
{
t=n[j];
n[j]=n[j+1];
n[j+1]=t;
}
}
}
}
public static void main(String arg[])
{
BubbleSortProject ob=new BubbleSortProject();
System.out.println("Before Sort");
ob.Process();
ob.BubbleSort();
System.out.println("After Sort");
ob.Process();
}
}
Output:
Before Sort
8 18 20 6 1 4 19 16 15 3
After Sort
20 19 18 16 15 8 6 4 3 1
Output:
Before Sort
8 18 20 6 1 4 19 16 15 3
After Sort
20 19 18 16 15 8 6 4 3 1