DSA/algorithms/Java/sorting/bubble-sort.java

41 lines
941 B
Java
Raw Normal View History

import java.util.Scanner;
public class sorting {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
2021-04-17 00:49:56 +00:00
boolean sorted = true;
2021-04-17 00:49:56 +00:00
System.out.println("Enter the size of array: ");
int n=sc.nextInt();
2021-04-17 00:49:56 +00:00
int a[]=new int[n];
2021-04-17 00:49:56 +00:00
System.out.println("Enter the elements of array : ");
for (int i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
2021-04-17 00:49:56 +00:00
for (int i=0;i<n-1;i++)
{
for(int j = 0; j < n - 1 - i; j++)
{
if(a[j+1]<a[j])
{
int temp=a[j+1];
a[j+1]=a[j];
a[j]=temp;
sorted =false;
}
}
if(sorted)break;
}
System.out.println("Array after sorting :");
for (int item:a)
{
System.out.print(item+" ");
}
}
}