📜  气泡排序算法

📅  最后修改于: 2020-09-27 16:58:28             🧑  作者: Mango

在本教程中,您将学习气泡排序的工作原理。此外,您还将在C,C++,Java和Python找到冒泡排序的工作示例。

冒泡排序是一种算法,用于比较相邻元素,并在相邻元素未按预期顺序进行交换时交换它们的位置。顺序可以是升序或降序。


气泡排序如何工作?
  1. 从第一个索引开始,比较第一个和第二个元素,如果第一个元素大于第二个元素,则将它们交换。

    现在,比较第二个和第三个元素。如果它们不正常,请交换它们。

    上面的过程一直持续到最后一个元素。

    Bubble Sort Steps
    比较相邻元素
  2. 其余迭代将继续相同的过程。每次迭代后,未排序元素中的最大元素将放置在末尾。

    在每次迭代中,都会进行比较直到最后一个未排序的元素。

    当所有未排序的元素都放在其正确位置时,对数组进行排序。

    Bubble Sort Steps
    比较相邻元素
    Bubble Sort Steps
    比较相邻元素
    Bubble Sort steps
    比较相邻元素

气泡排序算法
bubbleSort(array)
  for i  rightElement
      swap leftElement and rightElement
end bubbleSort

Python,Java和C / C++示例
Python
爪哇
C
C++
# Bubble sort in Python


def bubbleSort(array):
    
    # run loops two times: one for walking throught the array 
    # and the other for comparison
    for i in range(len(array)):
        for j in range(0, len(array) - i - 1):

            # To sort in descending order, change > to < in this line.
            if array[j] > array[j + 1]:
                
                # swap if greater is at the rear position
                (array[j], array[j + 1]) = (array[j + 1], array[j])


data = [-2, 45, 0, 11, -9]
bubbleSort(data)
print('Sorted Array in Asc ending Order:')
print(data)
// Bubble sort in Java

import java.util.Arrays;

class BubbleSort {
  void bubbleSort(int array[]) {
    int size = array.length;
    
    // run loops two times: one for walking throught the array
    // and the other for comparison
    for (int i = 0; i < size - 1; i++)
      for (int j = 0; j < size - i - 1; j++)

        // To sort in descending order, change > to < in this line.
        if (array[j] > array[j + 1]) {

          // swap if greater is at the rear position
          int temp = array[j];
          array[j] = array[j + 1];
          array[j + 1] = temp;
        }
  }

  // driver code
  public static void main(String args[]) {
    int[] data = { -2, 45, 0, 11, -9 };
    BubbleSort bs = new BubbleSort();
    bs.bubbleSort(data);
    System.out.println("Sorted Array in Ascending Order:");
    System.out.println(Arrays.toString(data));
  }
}
// Bubble sort in C

#include 

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 " 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);
}
// Bubble sort in C++

#include 
using namespace std;

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 < in this line.
      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) {
    cout << "  " << array[i];
  }
  cout << "\n";
}

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

优化气泡排序

在上面的代码中,即使数组已经排序,也进行了所有可能的比较。它增加了执行时间。

通过引入额外的变量swap可以优化代码。每次迭代之后,如果没有交换发生,则无需执行其他循环。

在这种情况下,将变量swap设置为false。因此,我们可以防止进一步的迭代。

优化气泡排序的算法是

bubbleSort(array)
  swapped  rightElement
      swap leftElement and rightElement
      swapped 

优化的气泡排序示例

Python
爪哇
C
C +
# Optimized bubble sort in python


def bubbleSort(array):
    
    # Run loops two times: one for walking throught the array
    # and the other for comparison
    for i in range(len(array)):
        
        # swapped keeps track of swapping
        swapped = True
        for j in range(0, len(array) - i - 1):

            # To sort in descending order, change > to < in this line.
            if array[j] > array[j + 1]:

                # Swap if greater is at the rear position
                (array[j], array[j + 1]) = (array[j + 1], array[j])
                swapped = False
                
        # If there is not swapping in the last swap, then the array is already sorted.
        if swapped:
            break


data = [-2, 45, 0, 11, -9]
bubbleSort(data)
print('Sorted Array in Ascending Order:')
print(data)
// Optimized bubble sort in Java

import java.util.Arrays;

class BubbleSort {
  void bubbleSort(int array[]) {
    int size = array.length;

    // Run loops two times: one for walking throught the array
    // and the other for comparison
    for (int i = 0; i < size - 1; i++) {
 
      // swapped keeps track of swapping
      boolean swapped = true;
      for (int j = 0; j < size - i - 1; j++) {

        // To sort in descending order, change > to < in this line.
        if (array[j] > array[j + 1]) {
          
          // Swap if greater is at the rear position
          int temp = array[j];
          array[j] = array[j + 1];
          array[j + 1] = temp;
          
          swapped = false;
        }
      }
      
      // If there is not swapping in the last swap, then the array is already sorted.
      if (swapped == true)
        break;
    }
  }

  // Driver code
  public static void main(String args[]) {
    int[] data = { -2, 45, 0, 11, -9 };
    BubbleSort bs = new BubbleSort();
    bs.bubbleSort(data);
    System.out.println("Sorted Array in Ascending Order:");
    System.out.println(Arrays.toString(data));
  }
}
// Optimized bubble sort in C

#include 

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);
}
// Optimized bubble sort in C++

#include 
using namespace std;

void bubbleSort(int array[], int size) {
  for (int step = 0; step < size - 1; ++step) {
// Run loops two times: one for walking throught the array
    // and the other for comparison
    int swapped = 0;
    for (int i = 0; i < size - step - 1; ++i) {
      // To sort in descending order, change > to < in this line.
      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;
        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 printArray(int array[], int size) {
  for (int i = 0; i < size; ++i) {
    cout << "  " << array[i];
  }
  cout << "\n";
}

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

复杂

气泡排序是最简单的排序算法之一。该算法实现了两个循环。

Cycle Number of Comparisons
1st (n-1)
2nd (n-2)
3rd (n-3)
……. ……
last 1

比较次数: (n-1)+(n-2)+(n-3)+ ….. + 1 = n(n-1)/ 2几乎等于n 2

复杂度: O(n 2 )

同样,我们可以通过简单地观察循环数来分析复杂性。有2个循环,所以复杂度为n*n = n 2

时间复杂度:

  • 最坏情况下的复杂度: O(n 2 )
    如果我们要按升序排序,而数组按降序排序,则会发生最坏的情况。

  • 最佳案例复杂度: O(n)
    如果数组已经排序,则无需排序。

  • 平均案例复杂度: O(n 2 )
    当数组中的元素处于混乱顺序(既不升也不降)时,就会发生这种情况。

空间复杂度:
空间复杂度为O(1)因为交换使用了额外的变量temp

在优化算法中, 交换的变量增加了空间的复杂性,从而使其变为O(2)


气泡排序应用

在以下情况下使用冒泡排序:

  1. 代码的复杂程度无关紧要。
  2. 首选短代码。