Written by Sai Sameera Thota on December 30, 2012 in Java > Programming

Bubble Sort in Java

GET ALERTS:

Get our Latest updates delivered to your mailbox!

The following written is Bubble Sort in Java. You can get the source code below. The explanation for this code is same as Bubble Sort in C. This is based on Comparison and Swapping method.

import java.io.*;
class BubbleSort
{
    public static void sort(int size,int[] arr)
	{
		for(int i = 0;i<size;i++)
		{
			for(int j = 0;j<size;j++)
			{
                            if(arr[j]<arr[j-1])
                            {
                                int temp = arr[j];
                                arr[j]=arr[j-1];
                                arr[j-1]=temp;
                            }

			}
		}
		System.out.println("Elements after sorting");
		for(int i=0;i<size;i++)
		{
			System.out.print(arr[i]+" ");
		}
	}
	public static void main(String args[]) throws IOException
	{
		int[] array = new int[20];
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		System.out.println("Enter the size of array");
		int size = Integer.parseInt(br.readLine());
		System.out.println("Enter the elemnts of array : ");
		for(int i=0;i<size;i++)
		{
			 array[i] =Integer.parseInt(br.readLine());
		}
		System.out.println("Elements before sorting");
		for(int i=0;i<size;i++)
		{
			System.out.print(array[i]+" ");
		}
		System.out.println();
		sort(size,array);
	}
}

{ 0 comments… add one now }

Leave a Comment

Previous post:

Next post: