Data Structures Tutorial

Data Structures Tutorial Asymptotic Notation Structure and Union Array Data Structure Linked list Data Structure Type of Linked list Advantages and Disadvantages of linked list Queue Data Structure Implementation of Queue Stack Data Structure Implementation of Stack Sorting Insertion sort Quick sort Selection sort Heap sort Merge sort Bucket sort Count sort Radix sort Shell sort Tree Traversal of the binary tree Binary search tree Graph Spanning tree Linear Search Binary Search Hashing Collision Resolution Techniques

Misc Topic:

Priority Queue in Data Structure Deque in Data Structure Difference Between Linear And Non Linear Data Structures Queue Operations In Data Structure About Data Structures Data Structures Algorithms Types of Data Structures Big O Notations Introduction to Arrays Introduction to 1D-Arrays Operations on 1D-Arrays Introduction to 2D-Arrays Operations on 2D-Arrays Strings in Data Structures String Operations Application of 2D array Bubble Sort Insertion Sort Sorting Algorithms What is DFS Algorithm What Is Graph Data Structure What is the difference between Tree and Graph What is the difference between DFS and BFS Bucket Sort Dijkstra’s vs Bellman-Ford Algorithm Linear Queue Data Structure in C Stack Using Array Stack Using Linked List Recursion in Fibonacci Stack vs Array What is Skewed Binary Tree Primitive Data Structure in C Dynamic memory allocation of structure in C Application of Stack in Data Structures Binary Tree in Data Structures Heap Data Structure Recursion - Factorial and Fibonacci What is B tree what is B+ tree Huffman tree in Data Structures Insertion Sort vs Bubble Sort Adding one to the number represented an array of digits Bitwise Operators and their Important Tricks Blowfish algorithm Bubble Sort vs Selection Sort Hashing and its Applications Heap Sort vs Merge Sort Insertion Sort vs Selection Sort Merge Conflicts and ways to handle them Difference between Stack and Queue AVL tree in data structure c++ Bubble sort algorithm using Javascript Buffer overflow attack with examples Find out the area between two concentric circles Lowest common ancestor in a binary search tree Number of visible boxes putting one inside another Program to calculate the area of the circumcircle of an equilateral triangle Red-black Tree in Data Structures Strictly binary tree in Data Structures 2-3 Trees and Basic Operations on them Asynchronous advantage actor-critic (A3C) Algorithm Bubble Sort vs Heap Sort Digital Search Tree in Data Structures Minimum Spanning Tree Permutation Sort or Bogo Sort Quick Sort vs Merge Sort Boruvkas algorithm Bubble Sort vs Quick Sort Common Operations on various Data Structures Detect and Remove Loop in a Linked List How to Start Learning DSA Print kth least significant bit number Why is Binary Heap Preferred over BST for Priority Queue Bin Packing Problem Binary Tree Inorder Traversal Burning binary tree Equal Sum What is a Threaded Binary Tree? What is a full Binary Tree? Bubble Sort vs Merge Sort B+ Tree Program in Q language Deletion Operation from A B Tree Deletion Operation of the binary search tree in C++ language Does Overloading Work with Inheritance Balanced Binary Tree Binary tree deletion Binary tree insertion Cocktail Sort Comb Sort FIFO approach Operations of B Tree in C++ Language Recaman’s Sequence Tim Sort Understanding Data Processing Applications of trees in data structures Binary Tree Implementation Using Arrays Convert a Binary Tree into a Binary Search Tree Create a binary search tree Horizontal and Vertical Scaling Invert binary tree LCA of binary tree Linked List Representation of Binary Tree Optimal binary search tree in DSA Serialize and Deserialize a Binary Tree Tree terminology in Data structures Vertical Order Traversal of Binary Tree What is a Height-Balanced Tree in Data Structure Convert binary tree to a doubly linked list Fundamental of Algorithms Introduction and Implementation of Bloom Filter Optimal binary search tree using dynamic programming Right side view of binary tree Symmetric binary tree Trim a binary search tree What is a Sparse Matrix in Data Structure What is a Tree in Terms of a Graph What is the Use of Segment Trees in Data Structure What Should We Learn First Trees or Graphs in Data Structures All About Minimum Cost Spanning Trees in Data Structure Convert Binary Tree into a Threaded Binary Tree Difference between Structured and Object-Oriented Analysis FLEX (Fast Lexical Analyzer Generator) Object-Oriented Analysis and Design Sum of Nodes in a Binary Tree What are the types of Trees in Data Structure What is a 2-3 Tree in Data Structure What is a Spanning Tree in Data Structure What is an AVL Tree in Data Structure Given a Binary Tree, Check if it's balanced

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.



ADVERTISEMENT
ADVERTISEMENT