Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to sort array elements using Bubble Sort algorithm in Java ?


How Bubble Sort is implemented in Java ?. 
Bubble Sort is a special sorting technique, which sorts elements by making multiple passes. While making each pass neighboring elements are compared in pairs. Generally the order is important, if the comparison comes out in decreasing order the numbers are swapped. If the order comes out in ascending order the values remain unchanged. It is called as Bubble Sort technique because the large value in each pass sinks to bottom while the smaller value bubbles out to top. After first successful pass the largest elements becomes the last element and after second pass, second largest elements becomes the second last element. Bubble Sort is implemented in Java by below small program :    

package com.hubberspot.sort.example;

public class BubbleSort {
  
  public static void main(String[] args) {
    int[] numbers = {3, 4, 5, 6, 7, 2, -3, 4, 16, 14};
    sort(numbers);
    for (int i = 0; i < numbers.length; i++)
      System.out.print(numbers[i] + " ");
  }  
  
  public static void sort(int[] list) {
    boolean nextPass = true;
    
    for (int k = 1; k < list.length && nextPass; k++) {
      nextPass = false;
      for (int i = 0; i < list.length - k; i++) {
        if (list[i] > list[i + 1]) {
      
          int temp = list[i];
          list[i] = list[i + 1];
          list[i + 1] = temp;
          
          nextPass = true; 
        }
      }
    }
  }  
} 



Video tutorial to demonstrate how to sort an array using Bubble Sort algorithm in Java.








 
© 2021 Learn Java by Examples Template by Hubberspot