You are here

Bubble sort in Java

Bubble sort in Java to sort numbers of an array in ascending/descending order.

Bubble sort program in Java

import java.util.Scanner;

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]) /* For descending order use < */
        {
          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]);
  }
}

The average-case complexity of bubble sort is O(n2). That's why programmers prefer other sorting algorithms over it.

Download Bubble sort Java program.

Output of program:
Bubble sort Java program output

You can also use sort method of Arrays class to sort integers in ascending order, but remember that the method uses a variation of Quicksort algorithm.

import java.util.Arrays;

class Sort
{
  public static void main(String args[])
  {
    int data[] = { 4, -5, 2, 6, 1 };
   
    Arrays.sort(data);
   
    for (int c: data)
    {
      System.out.println(c);
    }
  }
}

Share this