Program for Bubble Sort

An array is a group of contiguous or related data items that share a common name. An array stores multiple data items of the same data type, in a contiguous block of memory, divided into a number of slots.Arrays of any type can be created and may have one or more dimensions.

To create an array, you first must create an array variable of the desired type. The general form of a one-dimensional array declaration is
type  var-name[ ];

Here type is the data type of an array which is to hold. By specifying declaring array no array actually exists. To create actual array you must allocate one using new and assign it to the array-variable. Its general form is given below:
array-var  =  new type[size];

Here size specifies the number of elements in the array. In this program, we read the 10 elements from keyboard and store them in array and after that we sort these elements using Bubble sort method.

Sorting is nothing but arranging the elements in particular order either ascending or descending order. Here, the Bubble sort is used in that the two adjacent elements are compared with each other. If the first number is greater than second number then we swap these two numbers otherwise no swapping of numbers. We use two loops one for 'pass' and other to check for the exchange.

import java.util.Scanner;

class BubbleSort {

 public static void main(String args[])
  int[] array = new int[10];
  Scanner scan = new Scanner(;
  System.out.println("Enter array elements in unsorted mannner...");
  for(int i=0;i<10;i++) {
   array[i] = scan.nextInt();
  for(int i=0;i<10;i++) {
   for(int j=0;j<(10-i-1);j++) {
    if(array[j]>array[j+1]) // Checking for less element
     /* Exchange greater element with smaller element */
     int temp=array[j];
  System.out.println("Array elements after sorting :: ");
  for(int i=0;i<10;i++) {
   System.out.print(array[i]+" ");
C:\>java BubbleSort
Enter array elements in unsorted mannner...
56 44 22 46 95 41 19 52 74 60
Array elements after sorting :: 
19 22 41 44 46 52 56 60 74 95


Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to draw Smiley in Applet