Bubble Sort Algorithm Last Updated : 21 Jan, 2025 Comments Improve Suggest changes Like Article Like Report Try it on GfG Practice Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the first pass, the maximum element goes to end (its correct position). Same way, after second pass, the second largest element goes to second last position and so on.In every pass, we process only those elements that have already not moved to correct position. After k passes, the largest k elements must have been moved to the last k positions.In a pass, we consider remaining elements and compare all adjacent and swap if larger element is before a smaller element. If we keep doing this, we get the largest (among the remaining elements) at its correct position.How does Bubble Sort Work?Below is the implementation of the bubble sort. It can be optimized by stopping the algorithm if the inner loop didn't cause any swap. C++ #include <bits/stdc++.h> using namespace std; // An optimized version of Bubble Sort void bubbleSort(vector<int>& arr) { int n = arr.size(); bool swapped; for (int i = 0; i < n - 1; i++) { swapped = false; for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { swap(arr[j], arr[j + 1]); swapped = true; } } // If no two elements were swapped, then break if (!swapped) break; } } // Function to print a vector void printVector(const vector<int>& arr) { for (int num : arr) cout << " " << num; } int main() { vector<int> arr = { 64, 34, 25, 12, 22, 11, 90 }; bubbleSort(arr); cout << "Sorted array: \n"; printVector(arr); return 0; } C // Optimized implementation of Bubble sort #include <stdbool.h> #include <stdio.h> void swap(int* xp, int* yp){ int temp = *xp; *xp = *yp; *yp = temp; } // An optimized version of Bubble Sort void bubbleSort(int arr[], int n){ int i, j; bool swapped; for (i = 0; i < n - 1; i++) { swapped = false; for (j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { swap(&arr[j], &arr[j + 1]); swapped = true; } } // If no two elements were swapped by inner loop, // then break if (swapped == false) break; } } // Function to print an array void printArray(int arr[], int size){ int i; for (i = 0; i < size; i++) printf("%d ", arr[i]); } int main(){ int arr[] = { 64, 34, 25, 12, 22, 11, 90 }; int n = sizeof(arr) / sizeof(arr[0]); bubbleSort(arr, n); printf("Sorted array: \n"); printArray(arr, n); return 0; } Java // Optimized java implementation of Bubble sort import java.io.*; class GFG { // An optimized version of Bubble Sort static void bubbleSort(int arr[], int n){ int i, j, temp; boolean swapped; for (i = 0; i < n - 1; i++) { swapped = false; for (j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { // Swap arr[j] and arr[j+1] temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; swapped = true; } } // If no two elements were // swapped by inner loop, then break if (swapped == false) break; } } // Function to print an array static void printArray(int arr[], int size){ int i; for (i = 0; i < size; i++) System.out.print(arr[i] + " "); System.out.println(); } // Driver program public static void main(String args[]){ int arr[] = { 64, 34, 25, 12, 22, 11, 90 }; int n = arr.length; bubbleSort(arr, n); System.out.println("Sorted array: "); printArray(arr, n); } } Python # Optimized Python program for implementation of Bubble Sort def bubbleSort(arr): n = len(arr) # Traverse through all array elements for i in range(n): swapped = False # Last i elements are already in place for j in range(0, n-i-1): # Traverse the array from 0 to n-i-1 # Swap if the element found is greater # than the next element if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] swapped = True if (swapped == False): break # Driver code to test above if __name__ == "__main__": arr = [64, 34, 25, 12, 22, 11, 90] bubbleSort(arr) print("Sorted array:") for i in range(len(arr)): print("%d" % arr[i], end=" ") C# // Optimized C# implementation of Bubble sort using System; class GFG { // An optimized version of Bubble Sort static void bubbleSort(int[] arr, int n){ int i, j, temp; bool swapped; for (i = 0; i < n - 1; i++) { swapped = false; for (j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) { // Swap arr[j] and arr[j+1] temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; swapped = true; } } // If no two elements were // swapped by inner loop, then break if (swapped == false) break; } } // Function to print an array static void printArray(int[] arr, int size){ int i; for (i = 0; i < size; i++) Console.Write(arr[i] + " "); Console.WriteLine(); } // Driver method public static void Main(){ int[] arr = { 64, 34, 25, 12, 22, 11, 90 }; int n = arr.Length; bubbleSort(arr, n); Console.WriteLine("Sorted array:"); printArray(arr, n); } } JavaScript // Optimized javaScript implementation // of Bubble sort function bubbleSort(arr, n){ var i, j, temp; var swapped; for (i = 0; i < n - 1; i++){ swapped = false; for (j = 0; j < n - i - 1; j++){ if (arr[j] > arr[j + 1]) { // Swap arr[j] and arr[j+1] temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; swapped = true; } } // IF no two elements were // swapped by inner loop, then break if (swapped == false) break; } } // Function to print an array function printArray(arr, size){ var i; for (i = 0; i < size; i++) console.log(arr[i] + " "); } // Driver program var arr = [ 64, 34, 25, 12, 22, 11, 90 ]; var n = arr.length; bubbleSort(arr, n); console.log("Sorted array: "); printArray(arr, n); PHP <?php // PHP Optimized implementation // of Bubble sort function bubbleSort(&$arr) { $n = sizeof($arr); // Traverse through all array elements for($i = 0; $i < $n; $i++) { $swapped = False; // Last i elements are already // in place for ($j = 0; $j < $n - $i - 1; $j++) { // Traverse the array from 0 to // n-i-1. Swap if the element // found is greater than the // next element if ($arr[$j] > $arr[$j+1]) { $t = $arr[$j]; $arr[$j] = $arr[$j+1]; $arr[$j+1] = $t; $swapped = True; } } // If no two elements were swapped // by inner loop, then break if ($swapped == False) break; } } // Driver code $arr = array(64, 34, 25, 12, 22, 11, 90); $len = sizeof($arr); bubbleSort($arr); echo "Sorted array: \n"; for($i = 0; $i < $len; $i++) echo $arr[$i]." "; // This code is contributed by ChitraNayal. ?> OutputSorted array: 11 12 22 25 34 64 90Complexity Analysis of Bubble Sort:Time Complexity: O(n2)Auxiliary Space: O(1)Please refer Complexity Analysis of Bubble Sort for details.Advantages of Bubble Sort:Bubble sort is easy to understand and implement.It does not require any additional memory space.It is a stable sorting algorithm, meaning that elements with the same key value maintain their relative order in the sorted output.Disadvantages of Bubble Sort:Bubble sort has a time complexity of O(n2) which makes it very slow for large data sets.Bubble sort has almost no or limited real world applications. It is mostly used in academics to teach different ways of sorting.Recursive Bubble SortCoding practice for sortingQuiz on Bubble SortComplexity Analysis of Bubble Sort Comment More infoAdvertise with us Next Article Recursive Bubble Sort kartik Follow Improve Article Tags : Sorting DSA redBus Algorithms-BubbleSort BubbleSort +1 More Practice Tags : redBusSorting Similar Reads Bubble Sort Algorithm Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. This algorithm is not suitable for large data sets as its average and worst-case time complexity are quite high.We sort the array using multiple passes. After the fir 8 min read Recursive Bubble Sort Background : Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in wrong order.Example: First Pass: ( 5 1 4 2 8 ) --> ( 1 5 4 2 8 ), Here, algorithm compares the first two elements, and swaps since 5 > 1. ( 1 5 4 2 8 ) --> ( 1 4 10 min read Time and Space Complexity Analysis of Bubble Sort The time complexity of Bubble Sort is O(n^2) in the worst-case scenario and the space complexity of Bubble sort is O(1). Bubble Sort only needs a constant amount of additional space during the sorting process. Complexity TypeComplexityTime ComplexityBest: O(n)Average: O(n^2)Worst: O(n^2)Space Comple 3 min read Bubble Sort in different languagessin() in CThe sin() function in C is a standard library function to find the sine value of the radian angle. It is used to evaluate the trigonometric sine function of an angle. It takes the radian angle as input and returns the sin of that angle. It is defined inside <math.h> header file. Syntax of sin( 1 min read Bubble Sort in C++Bubble Sort Algorithm is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. It is often used to introduce the concept of a sorting and is particularly suitable for sorting small datasets.In this article, we will learn how to impleme 4 min read C++ Program for Recursive Bubble SortBackground: Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. Following is the iterative Bubble sort algorithm : // Iterative Bubble Sort bubbleSort(arr[], n) { for (i = 0; i n-1; i++) // Last i elements are already 2 min read Bubble Sort - PythonBubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. Bubble Sort algorithm, sorts an array by repeatedly comparing adjacent elements and swapping them if they are in the wrong order. The algorithm iterates through the a 2 min read Bubble Sort algorithm using JavaScriptBubble sort algorithm is an algorithm that sorts an array by comparing two adjacent elements and swapping them if they are not in the intended order. Here order can be anything like increasing or decreasing. How Bubble-sort works?We have an unsorted array arr = [ 1, 4, 2, 5, -2, 3 ], and the task is 4 min read p5.js | Bubble SortBubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent elements if they are in the wrong order. In order to know more about it. Please refer Bubble Sort Approach: Create an array of random values and render a bar corresponding to that value in terms of height. C 2 min read Sorting an array in Bash using Bubble sortPrerequisite: Bubble Sort Given an array arr sort the array in ascending order using bash scripting. Examples: Input : 9 7 2 5 Output : Array in sorted order : 2 5 7 9 Approach : For sorting the array bubble sort is the simplest technique. Bubble sort works by swapping the adjacent elements if they 2 min read Visualization of Bubble SortSorting Algorithms Visualization : Bubble SortThe human brain can easily process visuals in spite of long codes to understand the algorithms. In this article, Bubble sort visualization has been implemented using graphics.h library. As we all know that bubble sort swaps the adjacent elements if they are unsorted and finally the larger one being 5 min read Visualizing Bubble sort using PythonPrerequisites: Introduction to Matplotlib, Introduction to PyQt5, Bubble Sort Learning any algorithm can be difficult, and since you are here at GeekforGeeks, you definitely love to understand and implement various algorithms. It is tough for every one of us to understand algorithms at the first go. 2 min read Bubble Sort Visualization using JavaScriptGUI(Graphical User Interface) helps in better understanding than programs. In this article, we will visualize Bubble Sort using JavaScript. We will see how the elements are swapped in Bubble Sort and how we get the final sorted array. We will also visualize the time complexity of Bubble Sort. Refer 4 min read Bubble sort visualizer using PyGameIn this article we will see how we can visualize the bubble sort algorithm using PyGame i.e when the pygame application get started we can see the unsorted bars with different heights and when we click space bar key it started getting arranging in bubble sort manner i.e after every iteration maximum 3 min read Visualizing Bubble Sort using Tkinter in PythonIn this article, we will use the Python GUI Library Tkinter to visualize the Bubble Sort algorithm. Tkinter is a very easy to use and beginner-friendly GUI library that can be used to visualize the sorting algorithms.Here Bubble Sort Algorithm is visualized which works by repeatedly swapping the ad 5 min read Bubble Sort for Linked List by Swapping nodes Given a singly linked list, sort it using bubble sort by swapping nodes. Examples:Input: 5 -> 1 -> 32 -> 10 -> 78Output: 1 -> 5 -> 10 -> 32 -> 78 Input: 20 -> 4 -> 3Output: 3 -> 4 -> 20Approach: To apply Bubble Sort to a linked list, we need to traverse the list m 10 min read Sorting Strings using Bubble Sort Given an array of strings arr[]. Sort given strings using Bubble Sort and display the sorted array. In Bubble Sort, the two successive strings arr[i] and arr[i+1] are exchanged whenever arr[i]> arr[i+1]. The larger values sink to the bottom and are hence called sinking sort. At the end of each pa 4 min read Sort an array using Bubble Sort without using loops Given an array arr[] consisting of N integers, the task is to sort the given array by using Bubble Sort without using loops. Examples: Input: arr[] = {1, 3, 4, 2, 5}Output: 1 2 3 4 5 Input: arr[] = {1, 3, 4, 2}Output: 1 2 3 4 Approach: The idea to implement Bubble Sort without using loops is based o 9 min read Bubble Sort On Doubly Linked List Given a doubly linked list, the task is to sort the linked list in non-decreasing order by using bubble sort.Examples: Input : head: 5<->3<->4<->1<->2Output : head: 1<->2<->3<->4<->5Input : head: 5<->4<->3<->2Output : head: 2<-> 15+ min read Bubble sort using two Stacks Prerequisite : Bubble Sort Write a function that sort an array of integers using stacks and also uses bubble sort paradigm. Algorithm: 1. Push all elements of array in 1st stack 2. Run a loop for 'n' times(n is size of array) having the following : 2.a. Keep on pushing elements in the 2nd stack till 6 min read Like