Bubble Sort

Bubble Sort is the simplest sorting algorithm that works by repeatedly checking and swapping the next adjacent elements if they are in wrong order.

Time complexity :

In Average/Worst Case : it usually takes n number of passes to sort an array and complexity becomes O(n^2)
In Best Case : it takes O(n) time complexity , and it happens only when the array is already sorted.

Bubble Sort Example :

// Java program to implement Bubble Sort 
class BubbleSortPT
{
void bubbleSort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
{
// swap arr[j+1] and arr[i]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}

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

// Main method to test the above code
public static void main(String args[])
{
BubbleSortPT ob = new BubbleSortPT();
int arr[] = {64, 34, 25, 12, 22, 11, 90};

ob.bubbleSort(arr);
System.out.println("Sorted array");
ob.printArray(arr);
}
}

OUTPUT

Sorted array
11 12 22 25 34 64 90

Summary

In this article we learnt about bubble sort and its time complexities.
Hope you liked it !