You are here

Java program to bubble sort

Java program to bubble sort: This code sorts numbers inputted by user using Bubble sort algorithm.

Java programming code

  1. import java.util.Scanner;
  2.  
  3. class BubbleSort {
  4.   public static void main(String []args) {
  5.     int n, c, d, swap;
  6.     Scanner in = new Scanner(System.in);
  7.  
  8.     System.out.println("Input number of integers to sort");
  9.     n = in.nextInt();
  10.  
  11.     int array[] = new int[n];
  12.  
  13.     System.out.println("Enter " + n + " integers");
  14.  
  15.     for (c = 0; c < n; c++)
  16.       array[c] = in.nextInt();
  17.    
  18.     for (c = 0; c < ( n - 1 ); c++) {
  19.       for (d = 0; d < n - c - 1; d++) {
  20.         if (array[d] > array[d+1]) /* For descending order use < */
  21.         {
  22.           swap       = array[d];
  23.           array[d]   = array[d+1];
  24.           array[d+1] = swap;
  25.         }
  26.       }
  27.     }
  28.  
  29.     System.out.println("Sorted list of numbers:");
  30.  
  31.     for (c = 0; c < n; c++)
  32.       System.out.println(array[c]);
  33.   }
  34. }

Complexity of bubble sort is O(n2) which makes it a less frequent option for arranging in sorted order when quantity of numbers is high.

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 sort method uses a variation of Quick sort algorithm.

  1. import java.util.Arrays;
  2.  
  3. class Sort
  4. {
  5.   public static void main(String args[])
  6.   {
  7.     int data[] = { 4, -5, 2, 6, 1 };
  8.    
  9.     Arrays.sort(data);
  10.    
  11.     for (int c: data)
  12.     {
  13.       System.out.println(c);
  14.     }
  15.   }
  16. }