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: 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.

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.

Invert Binary Tree in DAA

Invert Binary Tree: A binary tree is a tree in which each node of the tree contains two children, i.e., left children and right children. Let us suppose we have...

2 minutes read.

DAA: Dijkstra’s Algorithm (Shortest Path)

Dijkstra’s Algorithm (Shortest Path) Dijkstra’s algorithm finds the shortest distance from a source to all the vertices in a graph. This algorithm is used in network protocols like IS-IS and OSPF(Open...

3 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: 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: Algorithm to Find the Maximum Width of a Tree

Algorithm to Find the Maximum Width of a Tree The width of a binary tree is defined as the maximum number of nodes at a given level. The level having the...

5 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: Bubble Sort Algorithm on Linked List

Bubble Sort Algorithm on Linked List In this article, we will sort a 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 bubble sort technique...

4 minutes read.

DAA: KMP Algorithm

KMP ALGORITHM The KMP algorithm is abbreviated as the "Knuth Morris Pratt” algorithm. This algorithm was developed by all of them.  This algorithm searches a pattern of length m in a string...

10 minutes read.

Introduction to Sorting in DAA

DAA: What is Sorting? The technique in which a data structure is rearranged in decreasing order, increasing order, or in a specified order is called sorting. We apply to sort in our...

4 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.

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: 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.

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: 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.

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: 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.

Segregate the given Linked List in DAA

Segregate Even and Odd Nodes in a Linked List A linked list is a linear data structure in which each node has two blocks. One contains the node’s value or data,...

3 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.