DEV Community

l0l0l0l
l0l0l0l

Posted on

1 1

Bubble Sort in Java

Bubble sort is one of the simplest sorting algorithms and really intuitive to understand. We compare adjacent elements and see if their order is wrong (a[i] > a[j] for 1 <= i < j <= size of array; if array is to be in ascending order, and vice-versa). If yes, then swap them.

Implementation of Bubble Sort in Java:
import java.util.Scanner;
class BubbleSort {
  public static void main(String []args) {
    int n;
    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 (int i = 0; i < n; i++)
      array[i] = in.nextInt();

    for (int i = 0; i < n - 1; i++) {
   Boolean swapped = false;
      for (int j = 0; j < n - i - 1; j++) {
        if (array[j] > array[j+1]) /* For descending order use < */
        {
          int temp = array[j];
          array[j]= array[j+1];
          array[j+1] = temp;

      swapped = true;
        }
      }
   if(!swapped)
      break;
   } 
System.out.println("Sorted list of numbers:");
for (int i = 0; i < n; i++)
System.out.println(array[i]);
  }
}

Orignally posted on interviewbit.

Heroku

This site is built on Heroku

Join the ranks of developers at Salesforce, Airbase, DEV, and more who deploy their mission critical applications on Heroku. Sign up today and launch your first app!

Get Started

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more