×

Bubble Sort in Data Structures

Bubble Sort in C++

The bubble sort algorithm analyses two adjacent elements and swaps them until they are no longer in the desired order.

Each iteration moves each member of the array closer to the end, similar to how air bubbles rise to the surface of water. As a result, it's known as a bubble sort.

Algorithm of Bubble Sorting

In order to sort an array of n elements in increasing order, use the following commands:

bubbleSort(array)
  for i <- 1 to indexOfLastUnsortedElement-1
    if leftElement > rightElement
      swap leftElement and rightElement
end bubbleSort

How Bubble Sort Works?

Assume we're attempting to organise the components ascending.

  • The Initial Iteration (Compare and Swap)
  • Compare the first and second items starting with the first index.
    • The first and second elements are switched if the first is bigger than the second.
    • Compare and contrast the second and third items. If they're not in the right sequence, swap them.
    • The procedure continues until the last piece is compared.
Bubble Sort in C++

The Latter Iteration

  • The remaining iterations follow the same pattern.
  • The biggest element among the unsorted items is placed at the conclusion of each iteration.
Bubble Sort in C++
  • The comparison takes place up to the final unsorted element in each iteration.
Bubble Sort in C++
  • When all of the unsorted items are placed in their right placements, the array is sorted.
Bubble Sort in C++

Code for Bubble Sort in C

// Bubble sorting in C


#include <stdio.h>


// carry out the bubble sort
void bubbleSort(int str[], int size) {


  // loop over each str element
  for (int step = 0; step < size - 1; ++step) {
      
    // str element comparison loop
    for (int i = 0; i < size - step - 1; ++i) {
      
      // compare two components that are adjacent
      // To sort in descending order, replace > to <.
      if (str[i] > str[i + 1]) {
        
        // Swapping happens when items are not in the correct sequence.
        int temp = str[i];
        str[i] = str[i + 1];
        str[i + 1] = temp;
      }
    }
  }
}


// str printing
void printStr(int str[], int size) {
  for (int i = 0; i < size; ++i) {
    printf("%d  ", str[i]);
  }
  printf("\n");
}


int main() {
  int str[] = {-9, 46, 0, 17, -12};
  
  // determine the length of the array
  int size = sizeof(str) / sizeof(str[0]);


  bubbleSort(str, size);
  
  printf("Array Sorted in Ascending Order:\n");
  printArray(str, size);
}

The following output should be generated by this programme:

Output

Array Sorted in Ascending Order:
-12 -9 0 17 46

Bubble Sort Algorithm with Improvements

  • Even if the array is already sorted, the above technique does all comparisons.
  • This lengthens the execution process.
  • We can remedy this by swapping in an additional variable. If elements are swapped, the value of swapped is set to true. If not, it is set to false.
  • If no swapping occurs after an iteration, the value of swapped will be false. This indicates that the items have already been sorted and that no additional iterations are required.
  • This shortens the execution time and aids in the optimization of the bubble sort.

The optimised bubble sort algorithm is

bubbleSort(array)
  swapped <- false
  for i <- 1 to indexOfLastUnsortedElement-1
    if leftElement > rightElement
      swap leftElement and rightElement
      swapped <- true
end bubbleSort

Bubble Sort in C code that is optimised

// Bubble sort in C that is optimised


#include <stdio.h>


// carry out the bubble sort
void bubbleSort(int str[], int size) {


  // loop over the str elements
  for (int step = 0; step < size - 1; ++step) {
    
    // determine whether or not swapping happens  
    int swapped = 0;
    
    // to compare str members in a loop
    for (int i = 0; i < size - step - 1; ++i) {
      
      // two str items are compared
      // To sort in descending order, replace > to <.
      if (str[i] > str[i + 1]) {
        
        // Swapping happens when items are not in the correct sequence.
        int temp = str[i];
        str[i] = str[i + 1];
        str[i + 1] = temp;
        
        swapped = 1;
      }
    }
    
    // The absence of swapping indicates that the str is already sorted.
    // hence there is no need for further comparison
    if (swapped == 0) {
      break;
    }
    
  }
}


// str printing
void printStr(int str[], int size) {
  for (int i = 0; i < size; ++i) {
    printf("%d  ", str[i]);
  }
  printf("\n");
}


// primary method
int main() {
  int str[] = {-9, 46, 0, 17, -12};
  
  // determine the length of the array
  int size = sizeof(str) / sizeof(str[0]);


  bubbleSort(str, size);
  
  printf("Array Sorted in Ascending Order:n");
  printArray(str, size);
}

The following output should be generated by this programme:

Output

Array Sorted in Ascending Order:
-12 -9 0 17 46

Complexity for Bubble Sort

Time Complexity
Best CaseO(n)
Worst CaseO(n2)
AverageO(n2)
Space ComplexityO(1)
StabilityYes

Detail-oriented complexity

The nearby components are compared in Bubble Sort.

CycleNumber of comparisons
1st( n-1 )
2nd( n-2 )
3rd( n-3 )
Last1

As a result, the number of iterations is:

( n-1 ) + ( n-2 ) + ( n-3 ) + ..... + 1 = n ( n-1 ) / 2

That almost equals n2

As a result, Complexity: O (n2)

Also, as we can see from the code, bubble sort necessitates two loops. As a result, the complexity is n*n = n2.

Complexities of Time

  • Complexity in the worst-case scenario: O (n2)
    • The worst case scenario happens if we wish to sort in ascending order but the array is in descending order.
  • Complexity in the Best-Case Scenario: O (n)
    • When the array has already been sorted, the outer loop repeats n times, but the inner loop does not. As a result, there are only n possible comparisons. As a result, complexity follows a linear pattern.
  • Case Complexity on the Average: O (n2)
    • When the items of an array are jumbled together, this happens (neither ascending nor descending).

Complexity of Space

  • Because an additional variable is utilised for swapping, the space complexity is O(1).
  • Two more variables are utilised in the improved bubble sort method. As a result, the spatial complexity will be O(2).

Applications for Bubble Sorting

If you're using bubble sort,

  • Complexity is irrelevant.
  • Code that is short and basic is desirable.

Related Topics

Dijkstra’s vs Bellman-Ford Algorithm

The Dijkstra Algorithm One of the SSSP (Single Source Shortest Path) algorithms is Dijkstra's. As a result, it finds the shortest path between a source node and all other nodes in...

7 minutes read.

What are the types of Trees in Data Structure

Data structures Data management is called database management. This allows the computer to sort or organize the data for efficient retrieval. A data model is a system used to store, manage,...

6 minutes read.

What is a Height-Balanced Tree in Data Structure

A height-balanced tree is a type of binary tree. If the absolute difference between the heights of the left and right subtree is less than or equal to 1, then...

6 minutes read.

Find the fractional (n/kth) node in the linked list

Find the fractional (n/kth) node in the linked list In this problem, we have given a singly linked list and a number k. Here we need to find the (n/k)th element...

2 minutes read.

Trim a binary search tree

Implementation //writing a C++ program will help us eliminate the keys that are out of the league.  #include<bits/stdc++.h> using namespace std; //we are now creating a binary search tree node consisting of key left...

8 minutes read.

Implementation of Queue

Implementation of queue: We can implement the queue through the array and linked list. An array is the easiest way to implement the queue. When a queue is created with the...

7 minutes read.

CSS Text-indent

Text-indent The Text-indent property of CSS is used to set any first line’s indentation inside a text’s block. It describes the horizontal space amount that puts establish before the text line. It...

3 minutes read.

Sorting Algorithms

Sorting: In the data structure, sorting is the process by which you arrange the data in a logical order. This logical order can also be an ascending order or a...

7 minutes read.

Binary Tree vs Binary Search Tree: Data Structure

Difference Between Binary Tree and Binary Search Tree What is Binary Tree? A tree which each node can have utmost two children called binary tree. These children are referred as the ‘left...

3 minutes read.

Data Structure Infix to Postfix Conversion

Infix to Postfix Conversion The infix expression is easy to read and write by humans. In present time, we use the infix expression in our daily life but the computers are...

4 minutes read.

Types of Linked list

Single linked list  A single linked list is a linked list in which all nodes are connected with each other in sequence. Each node of a singly linked list has two...

7 minutes read.

Linked List Representation of Binary Tree

As we all know, a binary tree has a maximum of two children and helps us manage the info correctly. The word binary itself represents its meaning; we know that...

4 minutes read.

Binary Tree Inorder Traversal

The binary tree is a type of tree in which each and every node has atleast two children except the leaf nodes. We have various operations in the binary tree,...

4 minutes read.

What are Forest Trees in Data Structure

Data structure A data model manages and optimizes computer resources, and a database stores and manages data. It's one of many uses for data structures to hold data. Data structures come...

5 minutes read.

Recursion in Fibonacci

Fibonacci heap is considered to be a particular execution of the heap data structure that ultimately helps in making use of not just any number but the Fibonacci numbers. It...

3 minutes read.

What Should We Learn First? Trees or Graphs in Data Structures

A data structure is a database used to store and manage data and optimize and manage computing resources. A data structure is a form used intelligently and quickly to store,...

6 minutes read.

Permutation Sort or Bogo Sort

In Permutation Sort or Bogo Sort, you have been given one array, which consists of different values. You have to sort the array using BOGO sort. Let’s take an example: Input-...

3 minutes read.

Bubble Sort vs Quick Sort

In this article, we are going to compare two sorting techniques, Bubble sort and Quick Sort. In starting, we will first discuss the idea of sorting an array using bubble...

7 minutes read.

Asymptotic Notation

Asymptotic notation is expressions that are used to represent the complexity of algorithms. The complexity of the algorithm is analyzed from two perspectives:  Time complexitySpace complexity Time complexity The time complexity of an algorithm is the...

3 minutes read.

Implementation of stack

Implementation of stack: The stack can be implemented in two ways: using array and using a linked list. The pop and push operations in the array are simpler than the...

3 minutes read.