×

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

Introduction to Arrays

What exactly is an array? A group of related data pieces stored in contiguous memory regions is referred to as an array. It is the most basic data structure in which...

5 minutes read.

Given a Binary Tree Swap Nodes at K Height

Implementation // Writing a C++ program that will help us exchange the nodes.  #include<bits/stdc++.h> using namespace std; // Creating a binary tree node. struct __nod { int record; struct __nod *Lft, *Rt; }; // creating a function that will help...

8 minutes read.

2-3 Trees and Basic Operations on them

2-3 Trees, like any other AVL trees or B-trees, are just a type of Height Balanced Tree. 2-3 Trees are the B-trees of order 3. Like every other B-tree, the...

4 minutes read.

Finding the Minimum and Maximum Value of a Binary Tree

Implementation // Writing a C++ program that will help us find out the maximum and the minimum in a binary tree.  #include <bits/stdc++.h> #include <iostream> using namespace std; // creating a new class tree node. class...

5 minutes read.

Depth of binary tree

We all know that a binary tree is a kind of tree that helps us maintain the order and balance of the tree. It is a type of tree in...

4 minutes read.

Trie data structure

Trie data structure The term “trie” comes from the word “retrieval” which means getting information. The trie data structure is a sorted extension of tree-based data structure. The trie data structure...

5 minutes read.

Fundamental of Algorithms

An algorithm is a part of any programming solution or coding. If we have to make a solution then first we have to think of a clear idea about the...

13 minutes read.

Post-order traversal in a binary tree

We all know that postorder is a form of tree traversal to visit the tree's nodes, and it helps us reach out to the tree's nodes. Postorder means visiting the...

4 minutes read.

Semi-Structured data

In this article, we will discuss the semi-structured data. Data can be defined as the distinct piece of information that is gathered and translated for some purpose. It can be...

5 minutes read.

Inorder Successor in Binary Trees

The next node in the Inorder traversal of a binary tree is known as Inorder successor of that particular node. In a Binary Search Tree, the definition of Inorder successor can...

9 minutes read.

Stack Using Linked List

In the linked list implementation of the stack, we use a linked list as the primitive data structure to create the stack. It is called the dynamic implementation of the...

6 minutes read.

Reverse the Singly Linked List in C

Reverse the Singly Linked List in C This article has given a singly linked list and will reverse the linked list by changing the links between nodes. Example:                         Input:  2 -> 4...

3 minutes read.

Convert binary tree to a doubly linked list

Implementation //creating a C++ program for the transition of a binary tree into a linked list. #include <iostream> using namespace std; /* Firstly, let’s create a binary tree that will help us in setting...

4 minutes read.

Horizontal and Vertical Scaling

Being a software engineer, you would have designed a website or application and deployed it on any server. Imagine that the developed application starts getting popular, and many users engage...

6 minutes read.

Red-black Tree in Data Structures?

A type of binary tree which is known as the Red-Black tree, is a specialized and unique tree. What is the urgency or, to be more precise, the necessity of...

10 minutes read.

Operations on Queue in Data Structures

A queue is a linear structure where operations are done in a specific sequence. Queues are abstract data structures that are comparable to Stacks. A queue, unlike a stack, is...

8 minutes read.

Linear vs Binary Search: Data Structure

Difference Between Linear and Binary Search What is Linear Search? A linear search also referred as a sequential search. It is a way to find an element within a list and it...

3 minutes read.

Hashing

Hashing: Hashing is a process in which a large amount of data is mapped to a small table with the help of hashing function. It is a searching technique. Hash table We...

4 minutes read.

Insertion Sort in Data Structures

Insertion Sort in C++ Insertion sort is a sorting algorithm that, in each iteration, installs an unsorted element in its proper position Insertion sort operates in a similar way to how we...

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.