How is a bubble sort algorithm implemented?

How is a bubble sort algorithm implemented?

In this tutorial, you will learn about the bubble sort algorithm and its implementation in Java.

What is a Bubble Sort?

Bubble Sort is a sorting algorithm used to sort list items in ascending order by comparing two adjacent values.

Basically, This sorting algorithm is the comparison-based algorithm in which each pair of adjacent elements is compared and the elements are swapped if they are not in order.

Bubble Sort Technique

Now we need to know the core concept of the bubble sort. Using this sorting technique, sorting is done in passes or iteration. Thus at the end of each iteration, the heaviest element is placed at its proper place in the list. In other words, the largest element in the list bubbles up.

Working of Bubble Sort

Now, let's see the working of the Bubble sort algorithm.

First Iteration (Compare and Swap)

  • Starting from the first index, compare the first and the second elements.
  • If the first element is greater than the second element, they are swapped.
  • Now, compare the second and the third elements. Swap them if they are not in order.
  • The above process goes on until the last element.

Second Iteration

The same process goes on for the remaining iterations.

After each iteration, the largest element among the unsorted elements is placed at the end.

In each iteration, the comparison takes place up to the last unsorted element.

import java.util.Arrays;

class Main {

  // perform the bubble sort
  static void bubbleSort(int array[]) {
    int size = array.length;
    
    // loop to access each array element
    for (int i = 0; i < size - 1; i++)
    
      // loop to compare array elements
      for (int j = 0; j < size - i - 1; j++)

        // compare two adjacent elements
        // change > to < to sort in descending order
        if (array[j] > array[j + 1]) {

          // swapping occurs if elements
          // are not in the intended order
          int temp = array[j];
          array[j] = array[j + 1];
          array[j + 1] = temp;
        }
  }

  public static void main(String args[]) {
      
    int[] data = { -2, 45, 0, 11, -9 };
    
    // call method using class name
    Main.bubbleSort(data);
    
    System.out.println("Sorted Array in Ascending Order:");
    System.out.println(Arrays.toString(data));
  }
}
Related posts
(0) Comments
Write a comment
Loading