# Bubble Sort Algorithm: What It is, Flow Chart, Time Complexity, and Implementation

Bubble Sort Algorithm: In this tutorial, we will learn about bubble sort, its algorithm, flow chart, and its implementation using C, C++, and Python. By Raunak Goswami Last updated : August 12, 2023

We are going to look at the algorithm of one of the simplest and the easiest sorting technique. since algorithm are language independent so you can use this algorithm to write your code in any language that you prefer.

## Bubble Sort Algorithm

Bubble sort is the simplest sorting algorithm and is useful for small amounts of data, Bubble sort implementation is based on swapping the adjacent elements repeatedly if they are not sorted. Bubble sort's time complexity in both of the cases (average and worst-case) is quite high. For large amounts of data, the use of Bubble sort is not recommended.

The basic logic behind this algorithm is that the computer selects the first element and performs swapping by the adjacent element if required based on the kind of sorting i.e. ascending and descending till it reaches the last element this is known as a pass. The computer performs multiple such passes till all the elements are sorted or no more swapping is possible.

## Bubble Sort Algorithm Pseudo Code

Consider the below-given pseudo code for implementing a bubble sort:

Bubble Sort(a[],n)For i=0 to n-1 Swap=false For j=i+1 to n if a[j-1] >a[j] Swap(a[j-1],a[j]) Swap=true Break if not swapped

## Bubble Sort Algorithm Flow chart

To help you understand better you can look at the flowchart for the bubble sort given below:

## Bubble Sort Using C

The below is the implementation of bubble sort using C program:

#include <stdio.h> void swap(int* x, int* y) { int temp = *x; *x = *y; *y = temp; } void bubble_sort(int arr[], int n) { int i, j; for (i = 0; i < n - 1; i++) for (j = 0; j < n - i - 1; j++) if (arr[j] > arr[j + 1]) swap(&arr[j], &arr[j + 1]); } int main() { int arr[] = { 12, 46, 34, 82, 10, 9, 28 }; int n = sizeof(arr) / sizeof(arr[0]); printf("\nInput Array: \n"); for (int i = 0; i < n; i++) printf("%d ", arr[i]); bubble_sort(arr, n); printf("\nSorted Array: \n"); for (int i = 0; i < n; i++) printf("%d ", arr[i]); return 0; }

The output of the above program will be:

Input Array: 12 46 34 82 10 9 28 Sorted Array: 9 10 12 28 34 46 82

## Bubble Sort Using C++

The below is the implementation of bubble sort using C++ program:

#include <iostream> using namespace std; int main() { int a[5]; int temp; for (int i = 0; i < 5; i++) { cin >> a[i]; } for (int j = 0; j < 4; j++) { for (int k = j + 1; k < 5; k++) if (a[j] > a[k]) { temp = a[k]; a[k] = a[j]; a[j] = temp; } } cout << "the elements after sorting" << endl; for (int i = 0; i < 5; i++) cout << a[i] << endl; return 0; }

The output of the above program will be:

1 2 3 6 4 the elements after sorting 1 2 3 4 6

## Bubble Sort Using Python

The below is the implementation of bubble sort using Python program:

import sys def bubble_sort(arr): # This function will sort the array in non-decreasing order. n = len(arr) #Traverse through all the array elements for i in range(n): # The inner loop will run for n-i-1 times as the # last i elements are already in place. for j in range(0, n-i-1): # Swap if the present element is greater than the # next element. if arr[j] > arr[j+1]: temp = arr[j] arr[j] = arr[j+1] arr[j+1] = temp return arr # main code if __name__=='__main__': arr = [2, 1, 9, 3, 7, 5, 6, 4, 8, 0] print("Sorted array: ") print(bubble_sort(arr))

The output of the above program will be:

Sorted array: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Related Tutorials

- Introduction to Algorithms
- Introduction to Greedy Strategy in Algorithms
- Stability in sorting
- External Merge Sorting Algorithm
- Radix Sort and its Algorithm
- Bucket Sort Algorithm
- Insertion sort Algorithm, flowchart and C, C++ Code
- Merge Sort | One of the best sorting algorithms used for large inputs
- Binary Search in C, C++
- Randomized Binary Search
- Meta Binary Search | One-sided Binary Search
- Difference between Linear Search and Binary Search
- Binary Search in String
- Variants of Binary Search
- Sieve of Eratosthenes to find prime numbers
- Optimal Merge Pattern (Algorithm and Example)
- Given an array of n numbers, Check whether there is any duplicate or not
- Finding the missing number
- Find the number occurring an odd number of times
- Find the pair whose sum is closest to zero in minimum time complexity
- Find three elements in an array such that their sum is equal to given element K
- Bitonic Search Algorithm
- Check whether a number is Fibonacci or not
- Segregate even and odd numbers in minimum time complexity
- Find trailing zeros in factorial of a number
- Find Nearest Greatest Neighbours of each element in an array
- Interpolation search algorithm
- Floor and ceil of an element in an array using C++
- Two Elements whose sum is closest to zero
- Find a pair with a given difference
- Count number of occurrences (or frequency) in a sorted array
- Find a Fixed Point (Value equal to index) in a given array
- Find the maximum element in an array which is first increasing and then decreasing
- Dynamic Programming (Components, Applications and Elements)
- Algorithm for fractional knapsack problem
- Algorithm and procedure to solve a longest common subsequence problem
- Dynamic Programming (Components, Applications and Elements)
- Find the Nth Fibonacci number | C++
- Longest Common Subsequence using Dynamic programming (DP)
- Longest Increasing Subsequence using Dynamic programming (DP)
- Find the maximum sub-array sum using KADANE'S ALGORITHM
- Non-intersecting chords using Dynamic Programming (DP)
- Edit Distance using Dynamic Programming (DP)
- Finding Ugly Number using Dynamic Programming (DP)
- Egg dropping problem using Dynamic Programming (DP)
- Wild card matching problem using Dynamic programming (DP)
- Compute sum of digits in all numbers from 1 to N for a given N
- Minimum jumps required using Dynamic programming (DP)
- Graph coloring problem's solution using backtracking algorithm
- Breadth First Search (BFS) and Depth First Search (DFS) Algorithms
- Travelling Salesman Problem
- Kruskal's (P) and Prim's (K) Algorithms
- Multistage graph problem with forward approach and backward approach algorithms
- Floyd Warshall algorithm with its Pseudo Code

- Backtracking (Types and Algorithms)
- 4 Queen's problem and solution using backtracking algorithm
- N Queen's problem and solution using backtracking algorithm
- Find the GCD (Greatest Common Divisor) of two numbers using EUCLID'S ALGORITHM
- Compute the value of A raise to the power B using Fast Exponentiation
- Implement First Come First Served (FCFS) CPU Scheduling Algorithm using C program
- Implementations of FCFS scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Non-Preemptive CPU scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Preemptive CPU scheduling algorithm using C++
- Implementation of Priority scheduling (Pre-emptive) algorithm using C++
- Implementation of Priority scheduling (Non Pre-emptive) algorithm using C++
- Implementation of Round Robin CPU Scheduling algorithm using C++
- Analysis of LRU page replacement algorithm and Belady's anomaly
- Branch and Bound
- Find the roots of a complex polynomial equation using Regula Falsi Method in C
- Sieve of Eratosthenes to find prime numbers
- Implementations of FCFS scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Non-Preemptive CPU scheduling algorithm using C++
- Implementation of Shortest Job First (SJF) Preemptive CPU scheduling algorithm using C++
- Implementation of Priority scheduling (Pre-emptive) algorithm using C++
- Divide and Conquer Paradigm (What it is, Its Applications, Pros and Cons)
- Implementation of Priority scheduling (Non Pre-emptive) algorithm using C++
- Implementation of Round Robin CPU Scheduling algorithm using C++
- Jump Search Implementation using C++
- Optimal Merge Pattern (Algorithm and Example)
- Introduction to Greedy Strategy in Algorithms
- Strassen's Matrix Multiplication in algorithms
- Huffman Coding (Algorithm, Example and Time complexity)
- Backtracking (Types and Algorithms)
- 4 Queen's problem and solution using backtracking algorithm
- N Queen's problem and solution using backtracking algorithm
- Graph coloring problem's solution using backtracking algorithm
- Tournament Tree and their properties
- Deterministic and Non Deterministic Algorithms
- Lower Bound Theory
- Non Recursive Tree Traversal Algorithm
- Line Drawing Algorithm
- Breadth First Search (BFS) and Depth First Search (DFS) Algorithms
- P and NP problems and solutions | Algorithms
- Travelling Salesman Problem
- 2 – 3 Trees Algorithm
- Kruskal's (P) and Prim's (K) Algorithms
- Algorithm for fractional knapsack problem
- Algorithm and procedure to solve a longest common subsequence problem
- Midpoint Circle Algorithm
- Multistage graph problem with forward approach and backward approach algorithms
- Floyd Warshall algorithm with its Pseudo Code
- Reliability design problem
- Removing consecutive duplicates from a string
- Fast Exponentiation using Bitmasking

Comments and Discussions!