DAA: Bubble Sort Algorithm

Bubble Sort Algorithm

The bubble sort algorithm is also known as the sinking algorithm. In this algorithm, we iterate over the array, and it takes two adjacent elements and swaps them if they are in the wrong order (ascending or descending). The step is continued until the whole array is sorted in a particular manner (ascending or descending).

Though the algorithm works poorly in real-world tools, due to its simplicity bubble sort algorithm is introduced as a primary tool when the algorithm concept is started.  This algorithm takes a lot of time when the number of exchanges is more.

After each pass, the highest element is pushed to the last position. Similarly, the process is followed to push the second-highest number to the second last position and so on.

The first loop runs for (N-1) iterations. The second pass loop will run for (N-2) positions and so on.

Time complexity

Worst case: O(n^2)

Best case: O(n)

Average case: O(n^2)

Space complexity: O(1)

Example - let arr[] = {14, 33, 27, 35, 10} and n = 5

DAA: Bubble Sort Algorithm

Pass 1

                             14 < 33 No swap takes place

DAA: Bubble Sort Algorithm

Takes 33 and 27

DAA: Bubble Sort Algorithm

Compares 27 < 23

DAA: Bubble Sort Algorithm

After swap array becomes

DAA: Bubble Sort Algorithm

            Takes 33 and 35 compares to 33 < 35; no swap happens

DAA: Bubble Sort Algorithm

Takes 35 and 10 compares 10 < 35

DAA: Bubble Sort Algorithm

                             Swaps 10 and 35

DAA: Bubble Sort Algorithm

After pass 1,  35 has reached its original place in the array that is the last index. 

Pass 2

                             33 comes to its original place i.e, index 4.

DAA: Bubble Sort Algorithm

Pass 3

DAA: Bubble Sort Algorithm

Pass 4

DAA: Bubble Sort Algorithm

C++ code:

 #include <bits/stdc++.h>
 using namespace std;
 void swap(int *x, int *y)
 {
           int temp = *x;
           *x = *y;
           *y = temp;
 }
 // A function to implement bubble sort algorithm
 void bubbleSort(int arr[], int n)
 {
           int i, j;
           for (i = 0; i < n-1; i++) // Outer loop for comparing the ith element
           {
           for (j = 0; j < n-i-1; j++) // Inner loop for comparing the ith element with other elements
                    {
                    if (arr[j] > arr[j+1])
                              swap(&arr[j], &arr[j+1]);
                    }
 }
 }
 /* Function to print an sorted array */
 void printArray(int arr[], int size)
 {
           int i;
           for (i = 0; i < size; i++) // Iterate through the array
                    cout << arr[i] << " ";
           cout << endl;
 }
 int main()
 {
           int arr[] = {64, 34, 25, 12, 22, 11, 90};
           int n = sizeof(arr)/sizeof(arr[0]);
           bubbleSort(arr, n);
           cout<<"Sorted array: \n";
           printArray(arr, n);
           return 0;
 } 

C code:

 #include <stdio.h>
 // Swap function swaps two numbers
 void swap(int *x, int *y)
 {
           int temp = *x;
           *x = *y;
           *y = temp;
 }
 // A function to implement bubble sort algorithm
 void bubbleSort(int arr[], int n)
 {
 int i, j;
 for (i = 0; i < n-1; i++) // Outer loop for comparing the ith element
 {
           for (j = 0; j < n-i-1; j++) // Inner loop for comparing the ith element with other elements
                    {
                    if (arr[j] > arr[j+1])
                              swap(&arr[j], &arr[j+1]);
                    }
 }
 }
 /* Function to print an array */
 void printArray(int arr[], int size)
 {
           int i;
           for (i=0; i < size; i++)
                    printf("%d ", arr[i]);
           printf("\n");
 }
 // Main function to call bubble sort and print
 int main()
 {
           int arr[] = {64, 34, 25, 12, 22, 11, 90};  // The array to be sorted
           int n = sizeof(arr)/sizeof(arr[0]);
           bubbleSort(arr, n);
           printf("Sorted array: \n");
           printArray(arr, n);
           return 0;
 } 

Java code:

 class BubbleSortAlgorithm
 {
           void bubbleSort(int arr[])
           {
                    int n = arr.length;
                    for (int i = 0; i < n-1; i++)  // Outer loop for comparing ith element
                              for (int j = 0; j < n-i-1; j++)  // inner loop for comparing ith element with all other elements
                                       if (arr[j] > arr[j+1])
                                       {
                                                 // swap if greater i.e,  arr[j+1] and arr[j]
                                                 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 function to call bubble sort and print function
           public static void main(String args[])
           {
                    BubbleSort ob = new BubbleSort();
                    int arr[] = {64, 34, 25, 12, 22, 11, 90};
                    ob.bubbleSort(arr);
                    System.out.println("Sorted array");
                    ob.printArray(arr);
           }
 } 

Related Topics

DAA: Depth-First Search Algorithm

Depth-first search: DFS is a traversing algorithm of a graph or tree in which one node is taken as arbitrary, and with the help of that arbitrary node, all its...

6 minutes read.

Symmetric Trees in DAA

Symmetric Trees The trees that are mirror images of themselves are known as symmetric trees. Look at the following tree image below: The tree is symmetric as the left subtree is the mirror...

4 minutes read.

DAA: Application of DFS and BFS

Application of DFS and BFS Depth-first search and breadth-first searches are the most famous algorithms used in daily life and the programming world. Let us now explore each application in which...

3 minutes read.

DAA: Continuous Tree

Continuous Tree A continuous tree is the one in which the nodes from root to leaf path, the two adjacent node values, have a difference of 1. Input :          3                     /   \                   ...

5 minutes read.

DAA: Dynamic Programming

Dynamic Programming Introduction The technique of breaking a problem statement into subproblems and using the optimal result of subproblems as an optimal result of the problem statement is known as dynamic programming....

2 minutes read.

DAA: Insert a node in Binary Search Tree

Insert a node in Binary Search Tree (BST) We have a Binary search tree and a key. Insert the key in the binary search tree if not present. In the above figure,...

4 minutes read.

DAA: Algorithm of Right View of a Binary Tree

Algorithm of Right View of a Binary Tree The right view of a binary tree is the visible nodes from the right side of the tree. In the given tree, the visible...

5 minutes read.

DAA: Bead Sort Algorithm

Bead Sort Algorithm The bead sort is also known as the gravity sort algorithm. The algorithm is based on the natural phenomena of gravity. The phenomenon is the falling of things...

3 minutes read.

DAA: Construct a Tree from Inorder and Preorder Traversals

Construct a Tree from Inorder and Preorder Traversals We are given inorder and preorder traversals of a tree. We need to generate a tree from these traversals. Example: Inorder[]   = { 3, 1,...

4 minutes read.

DAA: Floyd Cycle Detection

Floyd Cycle Detection Floyd Cycle algorithm is one of the cycle detection algorithms to detect the cycle in a given singly linked list. In the Floyd Cycle algorithm, we have two pointers...

4 minutes read.

DAA: Breadth First Search (BFS) for a Graph

Breadth First Search (Bfs) For A Graph The algorithm in which all the graph nodes are traversed is known as the breadth-first search algorithm. In this algorithm, we select one node,...

5 minutes read.

DAA: Bottom view of a Binary Tree

Bottom view of a Binary Tree The bottom view of a binary tree is the number of nodes visible when viewed from the bottom. At every horizontal distance, there would be...

3 minutes read.

DAA: Density of a Binary Tree Algorithm

The Density of a Binary Tree Algorithm The density of a binary tree is defined as the ratio of the tree’s size to the tree’s height.  The height of the tree is...

2 minutes read.

Boyer Moore Algorithm

Boyer Moore Algorithm The Boyer Moore algorithm is a searching algorithm in which a string of length n and a pattern of length m is searched. It prints all the occurrences...

11 minutes read.

DAA: Insertion Sort Algorithm on Singly Link List

Insertion Sort Algorithm on Singly Link List We will sort a singly link list using the bubble sort technique. Example: Input : 20->30->40->10 Output :10->20->30->40 Input : 20->4->3 Output : 3->4->20 Sorting Technique The insertion sort technique works...

3 minutes read.

DAA: Binary Tree and its Categories

Binary Tree and its Categories The binary tree is a non-linear data structure in which there are 0 or utmost 2 nodes.  Each node has two children, i.e., left and right...

4 minutes read.

DAA: Expression Trees

Expression Trees Expression trees are those in which the leaf nodes have the values to be operated, and internal nodes contain the operator on which the leaf node will be performed. Example:...

4 minutes read.

DAA: Euclid Algorithm

Euclid Algorithm The Euclid algorithm finds the GCD of two numbers in the efficient time complexity. To find the GCD of two numbers, we take the two numbers’ common factors and multiply...

8 minutes read.

DAA: Find the Height or Maximum Depth of a Binary Tree

Find the Height or Maximum Depth of a Binary Tree We have a binary tree structure and we need to find its height. It is defined by the distance from the...

3 minutes read.

DAA: Bubble Sort Algorithm

Bubble Sort Algorithm The bubble sort algorithm is also known as the sinking algorithm. In this algorithm, we iterate over the array, and it takes two adjacent elements and swaps them...

3 minutes read.