Java program for Bubble Sort

Sorting of data can be integral part of processing the given input to produce required output. Sorting may be required to remove data objects which are far from the mean of the entire data. Currently there are many sorting techniuqes, those are used according to the size of the data and the purpose of sorting. The basic of all sorting techniques is Bubble sort.

How it works: Instead of searching entire array, it compares only the adjacent data elements. It continues it’s searching till the last of the array and after reaching end of the array, it searches for the next largest number in the array and this process continues for n times where n is the size of the array.

import java.util.*;
import java.io.*;

public class bubble {
	public static void main(String args[]){

		int i,j,swap;
		Scanner in = new Scanner(System.in);
		System.out.println("\nEnter the size of the data to be sorted:");
		int size = in.nextInt();

		//Input from User
		int[] data = new int[size];
		for(i=0;i<size;i++){
			System.out.println("\nEnter " + (i+1) +" data value:");
			data[i] = in.nextInt();
		}

		//Request for choice
		System.out.println("\n\t1.Ascending order\n\n\t2.Descending order");
		System.out.println("\nEnter your choice from the above menu:");
		int choice = in.nextInt();

		
		if(choice == 1){
			/*Ascending order*/
			for(i=0;i<size;i++){
				for(j=0;j<size-1;j++){
					if(data[j] > data[j+1]){
						swap      = data[j];
          				data[j]   = data[j+1];
          				data[j+1] = swap;
					}
				}
			}
		}

		else {
			/*Descending order*/
			for(i=0;i<size;i++){
				for(j=0;j<size-1;j++){
					if(data[j] < data[j+1]){
						swap      = data[j];
          				data[j]   = data[j+1];
          				data[j+1] = swap;
					}
				}
			}
		}

		//Display the sorted data to user
		if(choice == 1){
			System.out.println("\nData in ascending order is\n");
			for(i=0;i<size;i++)
				System.out.print("\t" + data[i]);
		}
		else if(choice == 2){
			System.out.println("\nData in descending order is\n");
			for(i=0;i<size;i++)
				System.out.print("\t" + data[i]);
		}
		else 
			System.out.print("Wrong choice");
	}
}

Output:
bubble

Download Source Code

Advertisements
This entry was posted in Java and tagged , , , , , , , , , , , , , . Bookmark the permalink.

2 Responses to Java program for Bubble Sort

  1. Pingback: Java program for Insertion Sort | Letusprogram

  2. Pingback: Bubble sort in C | Letusprogram

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s