# Bubble Sort in Java

## What is Bubble Sort in JAVA?

Bubble Sort is the elementary sorting algorithm for sorting various data structure. It is a comparison based sorting algorithm in which each element is compared with the next element, and is swapped if those elements are not in the correct order.

• The algorithm starts with comparing the first pair of elements.
• If the first element is smaller then the second element, then the elements are interchanged, otherwise the order remains intact.
• This algorithm is not suitable for large data sets ## Implementation of bubble sort in JAVA

• First we will take starting two elements from the list.
• Then we will compare those elements.
• If these elements are found in unsorted order we will sort them.
• Else we will compare next to elements.
• We will repeat previous steps until we get our sorted array. ## Algorithm for Bubble Sort in JAVA

• Step1: Repeat step 1 to 4 for i=0 to n
• Step2: For j=0 to n
• Step3: if(arr[j]>arr[j+1]
• Step4: swap(arr[j],arr[j+1])
• Step5: End ## Program for bubble sort in JAVA

```class Main
{
void bubbleSort(int a[])
{
int len = a.length; // calculating the length of array
for (int i = 0; i < len-1; i++)
for (int j = 0; j < len-i-1; j++) if (a[j] > a[j+1]) //comparing the pair of elements
{
// swaping a[j+1] and a[i]
int temp = a[j];
a[j] = a[j+1];
a[j+1] = temp;
}
}

/* Prints the array */
void printArray(int a[])
{
int len = a.length;
for (int i=0; i<len; i++)
System.out.print(a[i] + " "); //printing the sorted array
System.out.println();
}

// Main method to test above
public static void main(String args[])
{
Main ob = new Main();
int a[] = {64, 34, 25, 12, 22, 11, 90};
ob.bubbleSort(a);//calling the bubbleSort function
System.out.println("Sorted array");
ob.printArray(a); //calling the printArray function
}
}```
```Sorted array
11 12 22 25 34 64 90
```

## Advantages of using Bubble Sort

LOL !!!! None, but if you still have to know then they could be –

• Bubble sort would need lesser memory then other sorting techniques.
• Even Noob Programmers can understand it

### Why Bubble sort Sucks !!!

• Its, time complexity is O(n2), which is shit
• When you have very large items then, it sucks even more as it becomes even more slow thanks to O(n2)
• The algorithm will be slowest when the array is sorted by in reverse
• Best Case : O(n), when its already sorted ### 2 comments on “Bubble Sort in Java”

• ritik

what is the time complexity of bubble sort for all case ? 0
• HelpPrepInsta 0