Bubble Sorting Concept and Program for Java
Bubble Sort Program for Java
- What is Bubble sort?
Bubble Sort, also referred to as sinking sort, is a comparison-based algorithm i.e. comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted.
Let us understand it with a Java code:
Bubble sort Program
import java.util.*;
class Bubble{ //class name
public static void main(String args[]){
int i,j,temp;
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int[] a=new int[n];
System.out.println("Enter values");
for(i=0;i<n;i++){
a[i]=sc.nextInt();
}
System.out.println("Arranged values are");
for(i=0;i<n;i++){
int flag=0;
for(j=0;j<n-1;j++){
if(a[j]>a[j+1]){
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
flag=1;
}
}
if(flag==0){
break;
}
}
for( i=0;i<n;i++){
System.out.println(a[i]);
}
}
}
Hope you have understood the Bubble Sort now.
For more Program codes and videos visit my Youtube channel :
https://youtube.com/channel/UC27TQ7zJKapHF78bwvi5iVw
For more Posts based on Programming visit my Blog:http://studytable10.blogspot.com/
Thanks!!☺☺
Comments
Post a Comment
What's in your mind?