Java Programs

TheFestFever.com

Our aim is to connect students from campuses all over Delhi by making them aware of all Technical, Cultural, Management fests, workshops, Seminars organized by every college in Delhi.

Join Us Now

Program 35: Write a Java program to bubble sort.

Bubble.java

import java.util.Scanner;

//Class BubbleSort contains the method to perform bubbleSort.
class BubbleSort
{
	//Method to perform bubble sort.
	public static void bubbleSort(int[] arr)
	{
        for(int i=0; i < arr.length;i++)
        {
            for(int j=0; j < arr.length-1;j++)
            {
                if(arr[j]>arr[j+1])
                {
                    int temp=arr[j+1];
                    arr[j+1]=arr[j];
                    arr[j]=temp;
                }
            }
        }
	}
}

//Main class 
public class Bubble
{
	//Method to take input.
	public static int[] takeInput()
	{
		Scanner s = new Scanner(System.in);
		System.out.println("Enter the number of elements to be included in the array.");
		int size = s.nextInt();
		int arr[] = new int[size];
		
		System.out.println("Enter the element in the array");

		for (int i = 0; i < size; i++)
		{
			arr[i] = s.nextInt();
		}
		return arr;
	}
	
	//Method to print sorted array.
	public static void print(int[] arr)
	{
		for (int i = 0; i < arr.length; i++)
		{
			System.out.print(arr[i]+" ");
		}
	}
	
	//Main method.
	public static void main(String[] args)
	{
		int[] arr = takeInput();
		BubbleSort.bubbleSort(arr);
		System.out.println("Sorted Array");
		print(arr);
	}
}



If you have any suggestion or found any error in the above program, then do let us know at [email protected] or just comment below.