Understanding the bubble sort algorithm

    In this tutorial, you will learn how bubble sort works. In addition, you will also find examples of bubble sorting in C language.
    Bubble sort is an algorithm that compares adjacent elements, and if they do not conform to a predetermined order, exchange their positions. The order can be ascending or descending.

How does bubble sort work?
  1. Starting from the first index, the first and second elements are compared, and if the first element is greater than the second element, they are exchanged.
    Now, compare the second and third elements. If they are not in the right order, please swap them.
    Continue the above process until the last element.
    Insert picture description here
  2. For the remaining iterations, the same process continues. After each iteration, the largest element among the unsorted elements is placed at the end. (For example, after completing the first iteration of the above figure, the sorted elements are 45 and the unsorted elements are -2, 0, 11, -9)
    In each iteration, the comparison continues until the last unsorted element.
    When all unsorted elements are placed in their correct positions, the array will be sorted.
    Insert picture description here
    Insert picture description here
    Insert picture description here
Bubble sort algorithm
bubbleSort(array)
  for i <- 1 to indexOfLastUnsortedElement-1
    if leftElement > rightElement
      swap leftElement and rightElement
end bubbleSort
C example
// Bubble sort in C

#include <stdio.h>

void bubbleSort(int array[], int size) {
    
    

  // run loops two times: one for walking throught the array
  // and the other for comparison
  for (int step = 0; step < size - 1; ++step) {
    
    
    for (int i = 0; i < size - step - 1; ++i) {
    
    
      
      // To sort in descending order, change">" to "<".
      if (array[i] > array[i + 1]) {
    
    
        
        // swap if greater is at the rear position
        int temp = array[i];
        array[i] = array[i + 1];
        array[i + 1] = temp;
      }
    }
  }
}

// function to print the array
void printArray(int array[], int size) {
    
    
  for (int i = 0; i < size; ++i) {
    
    
    printf("%d  ", array[i]);
  }
  printf("\n");
}

// driver code
int main() {
    
    
  int data[] = {
    
    -2, 45, 0, 11, -9};
  int size = sizeof(data) / sizeof(data[0]);
  bubbleSort(data, size);
  printf("Sorted Array in Ascending Order:\n");
  printArray(data, size);
}
Optimize bubble sort

    In the above code, even if the array is sorted, all possible comparisons will be performed. It increases the execution time.
    By introducing an additional variable swapped, the code can be optimized. After each iteration, if no exchange occurs, no further loops need to be executed.
    In this case, the variable swapped is set to false. Therefore, we can prevent further iterations.
    The algorithm for optimizing bubble sort is:

bubbleSort(array)
  swapped <- false
  for i <- 1 to indexOfLastUnsortedElement-1
    if leftElement > rightElement
      swap leftElement and rightElement
      swapped <- true
end bubbleSort
C example
// Optimized bubble sort in C

#include <stdio.h>

void bubbleSort(int arrayay[], int size) {
    
    
  for (int step = 0; step < size - 1; ++step) {
    
    

    // Swapped keeps track of swapping
    int swapped = 0;

    // Run loops two times: one for walking throught the array
    // and the other for comparison
    for (int i = 0; i < size - step - 1; ++i) {
    
    

      // To sort in descending order, change > to < in this line.
      if (arrayay[i] > arrayay[i + 1]) {
    
    
        
        // Swap if greater is at the rear position
        int temp = arrayay[i];
        arrayay[i] = arrayay[i + 1];
        arrayay[i + 1] = temp;
        swapped = 1;
      }
    }

    // If there is not swapping in the last swap, then the array is already sorted.
    if (swapped == 0)
      break;
  }
}

// Function to print an array
void printarrayay(int arrayay[], int size) {
    
    
  for (int i = 0; i < size; ++i) {
    
    
    printf("%d  ", arrayay[i]);
  }
  printf("\n");
}

// Driver code
int main() {
    
    
  int data[] = {
    
    -2, 45, 0, 11, -9};
  int size = sizeof(data) / sizeof(data[0]);
  bubbleSort(data, size);
  printf("Sorted Array in Ascending Order:\n");
  printarrayay(data, size);
}
the complexity

    Bubble sort is one of the simplest sorting algorithms. The algorithm implements two cycles.

cycle Number of comparisons
the first time (n-1)
the second time (n-2)
the third time (n-3)
… … … …
the last time 1

    The number of comparisons (n-1) + (n-2) + (n-3) +…+ 1 = n(n-1) / 2 approximately equal to n 2 n^2n2 .
    Complexity: O(n 2 n^2n2 )
    In addition, we can analyze the complexity by simply observing the number of cycles. There are 2 loops, so the complexity is n*n=n 2 n^2n2 .
    time complexity

  • Worst case complexity: O( n 2 n^2n2 )
    If we want to sort in ascending order and the array is sorted in descending order, the worst case will occur.
  • Best-case complexity: O(n)
    If the array is already arranged, there is no need to sort.
  • Average case complexity: O( n 2 n^2n2 )
    This happens when the elements of the array are out of order (neither ascending nor descending).

    Space complexity: The
    space complexity is O(1), because an extra variable temp is used when swapping.
    In the optimization algorithm, the variable swapped increases the space complexity, making it O(2).

Bubble sort application

    Bubble sort is used in the following situations:

  1. The complexity of the code is not important.
  2. Short codes are preferred.
Reference documents

[1]Parewa Labs Pvt. Ltd.Bubble Sort Algorithm[EB/OL].https://www.programiz.com/dsa/bubble-sort,2020-01-01.

Guess you like

Origin blog.csdn.net/zsx0728/article/details/114693658