Bubble Sort

Algorithm

Input	Array of integers 
Output	Sorted array
Complexity	O(n^2).

Bubble_sort(A,n)//here A is an array with n elements and this algorithm sorts the element in A.
1.	Repeat steps 2 -5 for i=1 to n-1
2.	Set j := 1;[initializes pass pointer j]
3.	Repeat while (j<= n-i):[executes passes]
4.	If A[j]>A[j+1] then:
    [interchange a[j] and a[j+1]].
Set j := j+1;
5.	[end of inner loop step 3]
6.	[end of outer loop step 1]
7.	Exit

Algorithm Description


C Code

#include<stdio.h>
#include<conio.h>
int main()
{
	int n,a[50],i,j,t;
	printf("Enter no of elements u want to enter ");
	scanf("%d",&n);
	printf("Enter elements\n");
	for(i=0;i<n;i++)
	{
		scanf("%d",&a[i]);
	}
	for(i=0;i<n;i++)
	{
		j=0;
		while(j<(n-i-1))
		{
			if(a[j]>a[j+1])
			{
				t=a[j];
				a[j]=a[j+1];
				a[j+1]=t;
			}
			j++;
		}
	}
	printf("Sorted Elements are :\n");
	for(i=0;i<n;i++)
	printf("%d\t",a[i]);
	return 0;
}


Java Code

import java.io.*;
class bubble
{
	public static void main(String args[]) throws Exception
	{
		int temp,n,i,j,k;
   	      BufferedReader cin= new BufferedReader (new InputStreamReader(System.in));
		System.out.println("enter the no. of elements");
		n=Integer.parseInt(cin.readLine());
		int arr[]=new int[n];
		System.out.println("enter the elements to be sorted");
		for(i=0;i<n;i++)
		{
			arr[i]= Integer.parseInt(cin.readLine());
		}
		
		for(k=1;k<n;k++)
		{
			for(j=0;j<n-k;j++)
			{
				if(arr[j]>arr[j+1])
				{
					temp=arr[j];
					arr[j]=arr[j+1];
					arr[j+1]=temp;
				}
			}
		}
		System.out.println("the elements after sorting are:");
		for(i=0;i<n;i++)
			System.out.println(arr[i]);
	}
}