Bubble Sort in Java

In this example, You learn about Bubble Sort in java.

Here you learn Java program for bubble sort, You are given a array and the task of the program to sort the array using bubble sort algorithm.

Learn in detail about bubble sort.

Bubble Sort Algorithm in Java

import java.util.Scanner;
public class BubbleSort {
 public static void main(String []args) {
    int n, c, d, swap;
    Scanner in = new Scanner(System.in);
    System.out.println("Input number of integers to sort");
    n = in.nextInt();
    int array[] = new int[n];
    System.out.println("Enter " + n + " integers");
    for (c = 0; c < n; c++)
        array[c] = in.nextInt();
    for (c = 0; c < ( n - 1 ); c++) {
        for (d = 0; d < n - c - 1; d++) {
            if (array[d] > array[d+1]) {
                swap = array[d];
                array[d] = array[d+1];
                array[d+1] = swap;
            }
        }
    }
    System.out.println("Sorted list of numbers");
    for (c = 0; c < n; c++)
    System.out.println(array[c]);
 }
}
Output

  
Input number of integers to sort
5

Enter 5 integers
2 6 2 1 5

Sorted list of numbers
1 2 2 5 6
You have any problem in the above Bubble Sort Java. Do not hesitate and write your problem in the comment box. I will support your problem

If you have any doubts, Please let me know

Previous Post Next Post

Contact Form