Bubble Sort in Java

Sorting often refers to arranging an array or collection of components in a specific order, such as ascending or descending order. Bubble Sort is the most straightforward sorting method, which repeatedly switches nearby components if they are in the wrong order. Due to its high average and worst-case time complexity, this approach is inappropriate for huge data sets.

A given array of numbers can be sorted using a variety of sorting algorithms. The Java Bubble Sort method is covered in this post. It is one of the most popular Sorting strategies.

To sort the array in ascending and descending order, we will talk about how it works and then put it into practice in Java. So let’s talk about Bubble Sort without spending any more time.

Describing the Bubble Sort

One of Java’s easiest methods for sorting array elements is the bubble sort. By comparing the adjacent items and exchanging them if they are not in the correct sequence, the goal is to move from the first element to the last one.

The greatest integer lies at the bottom of the array at the end of each iteration, precisely like the heaviest bubble in a vessel, which is why it is called the Bubble sort. The elements are switched until the array is sorted and no more switching is necessary.

The elements can be sorted in decreasing order, with the smallest element always placed at the end of the array throughout each iteration. Only by inverting the element’s weight is it possible to achieve this.

The following are some critical aspects of the Bubble sort:

  1. Where n represents the total number of elements in the array, the worst and average-case complexity of bubble sort is O(n2).
  2. Bubble sort’s best case complexity is O(n), where n is the array’s total number of items. Only when the given array is already sorted is this instance possible.
  3. The bubble sort algorithm uses O(1)’s auxiliary space
  4. One kind of Place Sorting is the Bubble Sort.
  5. The bubble sort algorithm is a stable one.

Note: By adding a few extra lines of code to the original code, we may improve the Bubble Sort algorithm and lower our complexity to the order of “n” (O(n)).

Whether the user submitted a sorted array, we may apply for only one pass and see if any swaps happen over the entire pass rather than using for all of them. If there are no swaps throughout the entire pass, the process is stopped, and the original array is returned. By including this piece of code, we can improve the algorithm’s efficiency while lowering its time complexity.

How Bubble Sort Works

Let’s say we want to arrange the components in ascending order.

  • Initial iteration (Compare and Swap)
  • Compare the first and second elements beginning with the first index. They are switched if the first element is greater than the second.
  • Compare the third and second items now. If they are out of order, swap them.
  • The method described above continues until the final component.
  • The remaining iterations follow the same procedure.
  • The most significant element among the unsorted elements is positioned at the end of each iteration. Up until the final unsorted element is compared on each iteration.
  • When all elements in an array are put in their proper placements, the array is considered sorted.
<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>codeBubbleSort(array)
  for i <- 1 to indexOfLastUnsortedElement-1
    if leftElement > rightElement
      swap leftElement and rightElement
end codeBubbleSort</pre>
</div>

Java Bubble Sort’s Operation

Next, we’ll explore how the Java Bubble Sort functions with the supplied array. We have an array, and it will take four iterations to sort it until we have a sorted array.

Java program to sort an array in ascending order using the bubble sort algorithm

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>package com.codeunderscored.bubblesort;

public class CodeBubbleSort {
  static void bubbleCode(int[] newArray) {
    int nVal = newArray.length;
    int tempVal = 0;
    for (int i = 0; i < nVal; i++) {
      for (int j = 1; j < ( nVal - i); j++) {
        if (newArray[j - 1] > newArray[j]) {

          //Change the elements with code
          tempVal = newArray[j - 1];
          newArray[j - 1] = newArray[j];
          newArray[j] = tempVal;
        }
      }
    }

  }
  public static void main(String[] args) {
    int newArray[] = {14, 25, 22,  31, 12, 35, 20, 28  };

    System.out.println("Array that we use Bubble Sort on: ");
    for (int i = 0; i < newArray.length; i++) {
      System.out.print(newArray[i] + " ");
    }
    System.out.println();

    bubbleCode(newArray); //Sorting the Array with Bubble sort

    System.out.println("array after bubble sorting: ");
    for (int i = 0; i < newArray.length; i++) {
      System.out.print(newArray[i] + " ");
    }
  }
}</pre>
</div>

An example of a Java bubble sort that sorts an array in descending order

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>package com.codeunderscored.bubblesort;

public class CodeBubbleSort {
  static void bubbleCode(int[] newArray) {
    int nVal = newArray.length;
    int tempVal = 0;
    for (int i = 0; i < nVal; i++) {
      for (int j = 1; j < (nVal - i); j++) {
        if (newArray[j - 1] < newArray[j]) {

          //Change the elements with code
          tempVal = newArray[j - 1];
          newArray[j - 1] = newArray[j];
          newArray[j] = tempVal;
        }
      }
    }
  }
  public static void main(String[] args) {
    int newArray[] = {14, 25, 22,  31, 12, 35, 20, 28  };

    System.out.println("The array that we apply Blob Sort: ");
    for (int i = 0; i < newArray.length; i++) {
      System.out.print(newArray[i] + " ");
    }
    System.out.println();

    bubbleCode(newArray); //Sorting the Array with Bubble sort

    System.out.println("array after bubble sorting: ");
    for (int i = 0; i < newArray.length; i++) {
      System.out.print(newArray[i] + " ");
    }

  }
}
</pre>
</div>

Java Bubble Sort usage

Since the Bubble Sort method is the most basic sorting method, it is frequently utilized in various software technologies. The Bubble Sort, for instance, is extremely helpful in computer graphics since it is used to find minute errors, such as switching between two elements and rectifying them with a linear complexity of 2n, where n is the array’s element count.

Benefits of Java’s Bubble Sort

The benefits of bubble sort include:

  • It is straightforward to understand and write.
  • Only a few lines of code are required.
  • Since bubble sort is an in-place sorting method and the data is already in the memory, there is little memory overhead.

Java Bubble Sort’s drawbacks

  • Additionally, bubble sort has a few downsides, including:
  • Sorting the array’s elements takes more time.
  • The array’s average time complexity gets more complex with more array elements.

Example: Bubble Sort in Java

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>public class CodeBubbleSort {  
    static void bubbleSort(int[] newArr) {  
        int n = newArr.length;  
        int tempVal = 0;  
         for(int i=0; i < n; i++){  
                 for(int j=1; j < (n-i); j++){  
                          if(newArr[j-1] > newArr[j]){  
                                 //swaping of the relevant elements  
                                 tempVal = newArr[j-1];  
                                 newArr[j-1] = newArr[j];  
                                 newArr[j] = tempVal;  
                         }  
                          
                 }  
         }  
  
    }  
    public static void main(String[] args) {  
                int newArr[] ={13,70,45,12,55,120,15};  
                 
                System.out.println("Bubble Sort Before Array");  
                for(int i=0; i < newArr.length; i++){  
                        System.out.print(newArr[i] + " ");  
                }  
                System.out.println();  
                  
                bubbleSort(newArr);//using bubble sort to order array elements
                 
                System.out.println("Bubble Sort After Array");  
                for(int i=0; i < newArr.length; i++){  
                        System.out.print(newArr[i] + " ");  
                }  
   
        }  
}  
</pre>
</div>

Example: Bubble Sort Implementation with Optimization

The abovementioned function will always run in O(n2) time even if the array is sorted. If the inner loop doesn’t result in any swap, it can be optimized by terminating the process. The above method is implemented as follows:

<div class="wp-block-codemirror-blocks-code-block code-block">
<pre>// Bubble sort has been optimized for Java.

import java.io.*;

class Codeunderscored
{
	// A more effective iteration of Bubble Sort
	static void codeBubbleSort(int arr[], int n)
	{
		int i, j, tmpVal;
		boolean swapStatus;
		for (i = 0; i < n - 1; i++)
		{
			swapStatus = false;
			for (j = 0; j < n - i - 1; j++)
			{
				if (arr[j] > arr[j + 1])
				{
					// swap arr[j] and arr[j+1]
					tmpVal = arr[j];
					arr[j] = arr[j + 1];
					arr[j + 1] = tmpVal;
					swapStatus = true;
				}
			}

			// If the inner loop did not switch any two elements, then break.
			if ( swapStatus == false)
				break;
		}
	}

	// Array printing function
	static void codePrintArray(int newArr[], int size)
	{
		int i;
		for (i = 0; i < size; i++)
			System.out.print(newArr[i] + " ");
		System.out.println();
	}

	// code for application training
	public static void main(String args[])
	{
		int newArr[] = { 84, 54, 45, 32, 42, 31, 120 };
		int nVal = newArr.length;
		codeBubbleSort(newArr, nVal);
		System.out.println("ordered array: ");
		codePrintArray(newArr, nVal);
	}
}</pre>
</div>

What is the Bubble sort’s Boundary Case?

When the items are already sorted, bubble sort takes the least time (Order of n). To prevent O(N2) time complexity, it is, therefore, best to determine in advance whether the array has previously been sorted or not.

Does Bubble Sort take place sorting?

Without using a significant data structure, bubble sort swaps nearby pairs. The bubble sort method is an in-place algorithm as a result.

How stable is the Bubble sort algorithm?

Bubble sorting is a stable algorithm, yes.

The Bubble Sort Algorithm is used where?

Bubble sort is frequently used to illustrate the idea of a sorting algorithm because it is straightforward. It is well-known in computer graphics for its ability to find a minimal fault (such as a swap of just two elements) and correct it with only linear complexity (2n).

In a polygon filling method, for instance, bounding lines are ordered by their x coordinate at a particular scan line (a line parallel to the x-axis). With incrementing y, only intersections of two lines will cause their order to change (two elements to be swapped).

Conclusion

In this article, you have learned about the bubble sort algorithm and how it is implemented in Java. A sorting method called bubble sort compares two nearby elements and swaps them until the intended order is broken. Each element of the array moves to the end in each iteration, much to the movement of air bubbles in the water that rise to the surface. Consequently, it is known as a bubble sort.

In this post, we looked at Java’s Bubble Sort and how it is used to arrange the elements in an array. It is pretty simple to comprehend. However, we inferred that it performs worse as the number of array elements increases and is most effective with small arrays.

We discovered how to sort an array in ascending and descending order with Java programs. Adding a few lines of code to the original code can also improve the bubble sort algorithm’s performance and effectiveness. After reading this tutorial, you will undoubtedly learn how to use Java’s Bubble Sort technique.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *