Sunday, May 17, 2015

Bubble sort program in java language


Bubble sorting program using java programming language
The java program given below is a bubble sort program, which is able to sort a collection of integer type numbers provided by the user. After running the program, the user will be asked to provide limit. That means, how many data he/she want to store. The 8th line of the program will display a message saying, "Enter the limit: ".

After providing the limit, it will be stored into an integer type variable limit by the 14th line. But, if we want to get any input then we must have to create Scanner Object as I have done by the 11th line. And we also import the Scanner package as like as the first line. In the 11th line I have created an Scanner Object named input, but you may name it anything as you like. As I have named it input, that's why I have used int limit = input.nextInt(); to store the limit.

By the 17th line, the user will be asked to store the data into the array. As I need to store data into an array, that's why I have declared an integer type array by the 20th line. In 23rd line there is a for-loop to store data into the array.
java program,bubble sorting program
import java.util.Scanner;
public class bubbleSort{
 public static void main(String args[]){
  //Declaring variables
  int i, j, temp;

  //Displaying message
  System.out.print("Enter the limit: ");

  //Creating scanner object
  Scanner input = new Scanner(System.in);
  
  //Storing the limit into variable
  int limit = input.nextInt();
  
  //Displaying message
  System.out.print("Enter the numbers: ");

  //Declaring integer type array
  int num[] = new int[limit];
  
  //for-loop for storing data into the array
  for(i=0; i<limit; i++){
   num[i] = input.nextInt();
  }
  
  //Displaying message
  System.out.print("The unsorted data into the array: ");

  //for-loop for displaying the unsorted data
  for(i=0; i<limit; i++){
   System.out.print(num[i]+", ");
  }
  
  //for-loop to sort the entered data
  for(i=0; i<limit; i++){
   for(j=0; j<limit-1; j++){
    if(num[j] > num[j+1]){
     //Data Swapping
     temp = num[j];
     num[j] = num[j+1];
     num[j+1] = temp;
    }
   }
  }
  
  //Displaying message
  System.out.print ("\nThe sorted data into the array: ");

  //for-loop for displaying the sorted data
  for(i=0; i<limit; i++){
   System.out.print(num[i]+", ");
  }
 }
}

Advertisement

No comments:

Post a Comment