Bubble sort in java
what is Bubble sort?
bubble sort is process to sort element from ascending to descending order or descending to ascending order
Steps to do this:-
1.take 5 integer variables i , j ,n , swap , temp
( i and j is for loop and n is for the length of the array swap is for checking condition and temp is for swapping method )
2. take a array
int a[]=new int[20]; // store any number for the length;
3. take a scanner class and scan the user input length
4. now we have to scan the array also so doing this we have to use a for loop
for(i=0;i<n;i++)
{
a[i]=s.nextInt(); // s is the scanner class object you can name it as your choice
}
now the time for calculation
we have to clear a thing is that if we enter 5 numbers of array it will take 4 steps to sort this the formula is
number of array-1= the sorting steps
lets do it
for(i=1;i<n;i++)
{
for(j=0;j<n-i;j++)
{
if(a[j]>a[j+1]
{
swap;
}
}
}
here we start the for loop from i=1 because of the principle of sorting and i for the sorting steps
an j is for sorting process we have a condition of j<n-i it means when i=1 and j=0 then it will compare the first two array
The Source Code
import java.util.Scanner;
class bubble
{
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int i,j,n,swap,temp;
int a[]=new int[20];
System.out.println("enter the length");
n=s.nextInt();
System.out.println("enter the elements");
for (i=0;i<n ;i++ )
{
a[i]=s.nextInt();
}
for(i=1;i<n;i++)
{
swap=0;
for (j=0;j<n-i ;j++ )
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
swap=1;
}
}
if (swap==0)
{
break;
}
}
System.out.println("after sort");
for (i=0;i<n ;i++ )
{
System.out.print(" "+a[i]);
}
}
}
OUTPUT
Watch My Video
Comments
Post a Comment
if you like it or have any doubts please let me know