Java Program to perform bubble sort

Here we are explaining how to write a java program to perform bubble sort.

What is bubble sort in java?

Bubble sort is a simple sorting algorithm. Here two adjacent numbers are checked, if the first number is greater than the second number then swapping is performed, and continue the checking with the next adjacent pairs. So after the first iteration, the biggest number is placed at its proper position.

How to implement a java program to perform bubble sort?

First, we have to declare the class BubbleSort.Declare the integer variables i,j,temp,limit.Create an object of the scanner class as sc. Read the limit of the array elements as a limit. Declare an integer array of size limit. Read the array elements using a for loop into array[i].Then by using nested for loop with the condition i<=limit-i-1,and j array[j+1],if true then change the position of array[j] to array[j+1] and repeat the loop.

Then we will display the array by using for loop as sorted list.

ALGORITHM

STEP 1: Declare the class BubbleSort with a public modifier.

STEP 2: Open the main() to start the program, Java program execution starts with the main()

STEP 3: Declare the integer variables i,j,temp,limit.

STEP 4: Read the limit of the array into the variable limit.

STEP 5: Declare an array of size limit.

STEP 6: Read the elements into the array by using for loop.

STEP 7: By using nested for loop compare the adjacent elements, if the first element is greater than the second element then swap the elements using temp variable.

STEP 8: Display the sorted list as array[i] using for loop.

 

Java Source Code

                                          import java.util.Scanner;

public class BubbleSort {
  public static void main(String []args) {
    int i,j,temp,limit;
    Scanner sc = new Scanner(System.in);
 
    System.out.println("Enter the limit of the numbers:");
    limit = sc.nextInt();
 
    int array[] = new int[limit];
 
    System.out.println("Enter " + limit + " numbers: ");
 
    for (i = 0; i <limit; i++) 
      array[i] = sc.nextInt();
 
    for (i = 0; i < ( limit - 1 ); i++) {
      for (j = 0; j < limit - i - 1; j++) {
        if (array[j] > array[j+1]) 
        {
           temp = array[j];
           array[j] = array[j+1];
           array[j+1] = temp;
        }
      }
    }
 
    System.out.println("******Sorted list******");
 
    for (i = 0; i < limit; i++) 
      System.out.println(array[i]);
  }
}
                                      

OUTPUT

Enter the limit of the numbers:5
Enter 5 numbers: 
9
10
23
7
4
******Sorted list******
4
7
9
10
23