Bubble Sort

 

Sample Input 1:
4
2 3 1 4
Sample Output 1:
Sorted Array -> 
1 2 3 4 

import java.util.Scanner;

public class BubbleSort {

	public static void main(String[] args) {
		Scanner s = new Scanner(System.in);
		int n=s.nextInt();
		int a[]=new int[n];
		for(int i=0;i<n;i++)
		{
			a[i]=s.nextInt();
		}
		
		bubbleSort(a);
		print(a);

	}
	
	public static void print(int a[])
	{
		System.out.println("Sorted Array -> ");
		for(int i=0;i<a.length;i++)
		{
			System.out.print(a[i]+" ");
		}
	}
	public static void bubbleSort(int[] a){
		
		int l=a.length;
		for(int i=0;i<l-1;i++)
		{
			for(int j=0;j<l-i-1;j++)
			{
				if(a[j]>a[j+1])
				{
					int t=a[j];
					a[j]=a[j+1];
					a[j+1]=t;
				}
			}
		}
	}

}

Comments

Popular posts from this blog

Minimum Length Word

Check Number Sequence

Star Pattern