📜  选择排序 VS 冒泡排序

📅  最后修改于: 2021-09-15 01:58:51             🧑  作者: Mango

在此,我们将介绍选择排序与冒泡排序之间的比较。基于时间和空间复杂度的选择排序和冒泡排序算法所需的资源如下。

时间复杂度 – O(n^2)相同的复杂性 – O(1)

让我们深入研究这些算法的工作原理。

选择排序
选择排序算法一般是教给我们的第一个排序算法。在这里,在内部循环的每次迭代中,最小元素被替换为每个循环中的起始元素。在每个循环结束后,我们将起始位置增加 1 并运行它直到数组中的倒数第二个元素。因此,通过在外循环结束时这样做,我们将拥有一个已排序的数组。

下图解释了选择排序算法的迭代。

这里我们可以简化选择排序算法,说这里的排序是按照从最小到最大的元素来完成的。首先排序最小的元素,然后排序第二小的元素,依此类推。

选择排序的实现:

下面是上述算法的实现。

C++
#include 
using namespace std;
void Selection_Sort(int arr[], int n) 
{
    for(int i = 0; i < n - 1; ++i) 
    {
        int min_index = i; 
        for(int j = i + 1; j < n; ++j) 
        {
            if(arr[j] < arr[min_index]) 
                min_index = j;
        }
        swap(arr[i], arr[min_index]); 
    }
}
int main()
{
    int n = 5;
    int arr[5] = {2, 0, 1, 4, 3};
    Selection_Sort(arr, n);
    cout<<"The Sorted Array by using Selection Sort is : ";
    for(int i = 0; i < n; ++i)
        cout<


Java
class GFG{
 
  static void Selection_Sort(int arr[], int n) 
  {
    for(int i = 0; i < n - 1; ++i) 
    {
      int min_index = i; 
      for(int j = i + 1; j < n; ++j) 
      {
        if(arr[j] < arr[min_index]) 
          min_index = j;
      }
      int temp = arr[i];
      arr[i] = arr[min_index];
      arr[min_index] = temp;
    }
  }
 
  // Driver code
  public static void main(String[] args)
  {
    int n = 5;
    int arr[] = {2, 0, 1, 4, 3};
    Selection_Sort(arr, n);
    System.out.print("The Sorted Array by using Selection Sort is : ");
    for(int i = 0; i < n; ++i)
      System.out.print(arr[i] + " ");
  }
}
 
// This code is contributed by aashish1995


Python3
def Selection_Sort(arr, n):
     
    for i in range(n - 1):
        min_index = i 
         
        for j in range(i + 1, n):
            if (arr[j] < arr[min_index]):
                min_index = j
                 
        arr[i], arr[min_index] = arr[min_index], arr[i] 
         
# Driver Code
n = 5
arr = [ 2, 0, 1, 4, 3 ]
Selection_Sort(arr, n)
 
print("The Sorted Array by using " \
      "Selection Sort is : ", end = '')
for i in range(n):
    print(arr[i], end = " ")
     
# This code is contributed by SHUBHAMSINGH10


C#
using System;
 
public class GFG{
 
  static void Selection_Sort(int []arr, int n) 
  {
    for(int i = 0; i < n - 1; ++i) 
    {
      int min_index = i; 
      for(int j = i + 1; j < n; ++j) 
      {
        if(arr[j] < arr[min_index]) 
          min_index = j;
      }
      int temp = arr[i];
      arr[i] = arr[min_index];
      arr[min_index] = temp;
    }
  }
 
  // Driver code
  public static void Main(String[] args)
  {
    int n = 5;
    int []arr = {2, 0, 1, 4, 3};
    Selection_Sort(arr, n);
    Console.Write("The Sorted Array by using Selection Sort is : ");
    for(int i = 0; i < n; ++i)
      Console.Write(arr[i] + " ");
  }
}
 
// This code is contributed by aashish1995


Javascript


C++
#include 
using namespace std;
void Bubble_Sort(int arr[], int n) 
{
    for(int i = 1; i < n; ++i)     
    {   
                for(int j = 0; j <= (n - i - 1); ++j)  
        {   
            if(arr[j] > arr[j + 1])
                swap(arr[j], arr[j + 1]); 
        }
    }
}
 
int main()
{
    int n = 5;
    int arr[5] = {2, 0, 1, 4, 3};
    Bubble_Sort(arr, n);
    cout<<"The Sorted Array by using Bubble Sort is : ";
    for(int i = 0; i < n; ++i)
        cout<


Java
import java.io.*;
 
class GFG{
     
static void Bubble_Sort(int arr[], int n) 
{
    for(int i = 1; i < n; ++i)     
    {
        for(int j = 0; j <= (n - i - 1); ++j)  
        {   
            if (arr[j] > arr[j + 1])
            {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            } 
        }
    }
}
 
// Driver code
public static void main(String[] args)
{
    int n = 5;
    int arr[] = { 2, 0, 1, 4, 3 };
     
    Bubble_Sort(arr, n);
     
    System.out.print("The Sorted Array by using Bubble Sort is : ");
    for(int i = 0; i < n; ++i)
        System.out.print(arr[i]+" ");
}
}
 
// This code is contributed by Shubhamsingh10


Python3
def Bubble_Sort(arr, n):
    for i in range(1, n):
        for j in range(0, n - i):
            if (arr[j] > arr[j + 1]):
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
                 
    return arr
     
# Driver Code
n = 5
arr = [ 2, 0, 1, 4, 3 ]
arr = Bubble_Sort(arr, n)
 
print("The Sorted Array by using Bubble Sort is : ", end = '')
for i in range(n):
    print(arr[i], end = " ")
 
# This code is contributed by Shubhamsingh10


C#
// C# program for the above approach
using System;
 
public class GFG{
     
    static void Bubble_Sort(int[] arr, int n) 
    {
        for(int i = 1; i < n; ++i)     
        {
            for(int j = 0; j <= (n - i - 1); ++j)  
            {   
                if (arr[j] > arr[j + 1])
                {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                } 
            }
        }
    }
     
    // Driver Code
    static public void Main ()
    {
        int n = 5;
        int[] arr = { 2, 0, 1, 4, 3 };
         
        Bubble_Sort(arr, n);
         
        Console.Write("The Sorted Array by using Bubble Sort is : ");
        for(int i = 0; i < n; ++i){
            Console.Write(arr[i]+" ");
        }
    }
}
 
// This code is contributed by Shubhamsingh10


Javascript


C++
// CPP program for the above approach
#include 
using namespace std;
 
// Function for bubble sort
void Bubble_Sort(int arr[], int n)
{
    bool flag;
   
    // Iterate from 1 to n - 1
    for (int i = 1; i < n; ++i) {
 
        flag = false;
       
        // Iterate from 0 to n - i - 1
        for (int j = 0; j <= (n - i - 1); ++j) {
            if (arr[j] > arr[j + 1]) {
                swap(arr[j], arr[j + 1]);
                flag = true;
            }
        }
        if (flag == false)
            break;
    }
}
 
// Driver Code
int main()
{
    int n = 5;
    int arr[5] = { 2, 0, 1, 4, 3 };
    Bubble_Sort(arr, n);
    cout << "The Sorted Array by using Bubble Sort is : ";
    for (int i = 0; i < n; ++i)
        cout << arr[i] << " ";
    return 0;
}


Java
// Java code for the above approach
import java.io.*;
 
class GFG{
     
// Function for bubble sort
static void Bubble_Sort(int[] arr, int n)
{
    boolean flag;
   
    // Iterate from 1 to n - 1
    for(int i = 1; i < n; ++i)
    {
        flag = false;
       
        // Iterate from 0 to n - i - 1
        for(int j = 0; j <= (n - i - 1); ++j)
        {
            if (arr[j] > arr[j + 1])
            {
                int temp  = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
                flag = true;
            }
        }
        if (flag == false)
            break;
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int n = 5;
    int[] arr = { 2, 0, 1, 4, 3 };
    Bubble_Sort(arr, n);
    System.out.print("The Sorted Array by " +
                     "using Bubble Sort is : ");
     
    for(int i = 0; i < n; ++i)
        System.out.print(arr[i] + " ");
}
}
 
// This code is contributed by shubhamsingh10


Python3
# Python program for the above approach
 
# Function for bubble sort
def Bubble_Sort(arr, n):
    flag = True
     
    # Iterate from 1 to n - 1
    for i in range(1,n):
        flag = False
        # Iterate from 0 to n - i - 1
        for j in range(n-i):
            if (arr[j] > arr[j + 1]):
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
                flag = True
         
        if (flag == False):
            break
         
# Driver Code
n = 5
arr = [2, 0, 1, 4, 3]
Bubble_Sort(arr, n)
print("The Sorted Array by using Bubble Sort is : ", end='')
for i in range(n):
    print(arr[i], end= " ")
 
# This code is contributed by ShubhamSingh10


C#
//C# code for the above approach
using System;
public class GFG{
     
    // Function for bubble sort
    static void Bubble_Sort(int[] arr, int n)
    {
        bool flag;
       
        // Iterate from 1 to n - 1
        for (int i = 1; i < n; ++i) {
     
            flag = false;
           
            // Iterate from 0 to n - i - 1
            for (int j = 0; j <= (n - i - 1); ++j) {
                if (arr[j] > arr[j + 1]) {
                    int temp  = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    flag = true;
                }
            }
            if (flag == false)
                break;
        }
    }
     
    // Driver Code
    static public void Main ()
    {
        int n = 5;
        int[] arr = { 2, 0, 1, 4, 3 };
        Bubble_Sort(arr, n);
        Console.Write("The Sorted Array by using Bubble Sort is : ");
        for (int i = 0; i < n; ++i)
            Console.Write(arr[i] + " ");
    }
 
}
 
// This code is contributed by shubhamsingh10.


输出
The Sorted Array by using Selection Sort is : 0 1 2 3 4 

冒泡排序
当我们第一次研究冒泡排序算法时,它可能看起来有点混乱。但这是对它的简单解释。这里交换以两种方式进行。在外循环的每次迭代中,找到最大的元素并与循环中的最后一个元素交换。在内部循环中,我们对两个连续元素进行成对交换。在每个内部循环中,我们从第一个元素到我们在前一个循环中少的一个元素。下图显示了冒泡排序算法中内循环的第一次迭代。

这里我们可以简化选择排序算法,说这里的排序是按照从最大到最小的元素来完成的。最大的元素首先保存在数组的最后一个位置。然后是倒数第二个位置中的第二大元素,依此类推。

冒泡排序的实现:
下面是上述算法的实现。

C++

#include 
using namespace std;
void Bubble_Sort(int arr[], int n) 
{
    for(int i = 1; i < n; ++i)     
    {   
                for(int j = 0; j <= (n - i - 1); ++j)  
        {   
            if(arr[j] > arr[j + 1])
                swap(arr[j], arr[j + 1]); 
        }
    }
}
 
int main()
{
    int n = 5;
    int arr[5] = {2, 0, 1, 4, 3};
    Bubble_Sort(arr, n);
    cout<<"The Sorted Array by using Bubble Sort is : ";
    for(int i = 0; i < n; ++i)
        cout<

Java

import java.io.*;
 
class GFG{
     
static void Bubble_Sort(int arr[], int n) 
{
    for(int i = 1; i < n; ++i)     
    {
        for(int j = 0; j <= (n - i - 1); ++j)  
        {   
            if (arr[j] > arr[j + 1])
            {
                int temp = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
            } 
        }
    }
}
 
// Driver code
public static void main(String[] args)
{
    int n = 5;
    int arr[] = { 2, 0, 1, 4, 3 };
     
    Bubble_Sort(arr, n);
     
    System.out.print("The Sorted Array by using Bubble Sort is : ");
    for(int i = 0; i < n; ++i)
        System.out.print(arr[i]+" ");
}
}
 
// This code is contributed by Shubhamsingh10

蟒蛇3

def Bubble_Sort(arr, n):
    for i in range(1, n):
        for j in range(0, n - i):
            if (arr[j] > arr[j + 1]):
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
                 
    return arr
     
# Driver Code
n = 5
arr = [ 2, 0, 1, 4, 3 ]
arr = Bubble_Sort(arr, n)
 
print("The Sorted Array by using Bubble Sort is : ", end = '')
for i in range(n):
    print(arr[i], end = " ")
 
# This code is contributed by Shubhamsingh10

C#

// C# program for the above approach
using System;
 
public class GFG{
     
    static void Bubble_Sort(int[] arr, int n) 
    {
        for(int i = 1; i < n; ++i)     
        {
            for(int j = 0; j <= (n - i - 1); ++j)  
            {   
                if (arr[j] > arr[j + 1])
                {
                    int temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                } 
            }
        }
    }
     
    // Driver Code
    static public void Main ()
    {
        int n = 5;
        int[] arr = { 2, 0, 1, 4, 3 };
         
        Bubble_Sort(arr, n);
         
        Console.Write("The Sorted Array by using Bubble Sort is : ");
        for(int i = 0; i < n; ++i){
            Console.Write(arr[i]+" ");
        }
    }
}
 
// This code is contributed by Shubhamsingh10

Javascript


输出
The Sorted Array by using Bubble Sort is : 0 1 2 3 4 

为冒泡排序添加智能:

  1. 我们必须考虑这样一个事实,即使我们的数据最初是排序的,我们当前的算法也会执行所有迭代。
  2. 如上面的代码所示,当 arr[i] > arr[i+1] 时,我们交换两个元素(比如 i 和 i+1)。因此,即使我们的数据已经排序(或在几次迭代后排序)我们的算法仍然会运行,
  3. 但是,我们可以调整我们的代码,以便我们的算法识别给定数据何时排序并且不需要进一步的迭代。
  4. 我们可以通过简单地添加一个“标志”变量来实现这一点。在内部循环外将此“标志”变量初始化为 false,如果在任何时候 ( arr[j] > arr[j+1] ) 条件为 true,则将其设置为 true。
  5. 退出内循环后,检查标志。如果flag == true即,它被更改并执行交换操作。但是,如果 flag == false,则意味着整个迭代没有执行交换,因此我们的数据现在已排序,不需要进一步的迭代。

C++

// CPP program for the above approach
#include 
using namespace std;
 
// Function for bubble sort
void Bubble_Sort(int arr[], int n)
{
    bool flag;
   
    // Iterate from 1 to n - 1
    for (int i = 1; i < n; ++i) {
 
        flag = false;
       
        // Iterate from 0 to n - i - 1
        for (int j = 0; j <= (n - i - 1); ++j) {
            if (arr[j] > arr[j + 1]) {
                swap(arr[j], arr[j + 1]);
                flag = true;
            }
        }
        if (flag == false)
            break;
    }
}
 
// Driver Code
int main()
{
    int n = 5;
    int arr[5] = { 2, 0, 1, 4, 3 };
    Bubble_Sort(arr, n);
    cout << "The Sorted Array by using Bubble Sort is : ";
    for (int i = 0; i < n; ++i)
        cout << arr[i] << " ";
    return 0;
}

Java

// Java code for the above approach
import java.io.*;
 
class GFG{
     
// Function for bubble sort
static void Bubble_Sort(int[] arr, int n)
{
    boolean flag;
   
    // Iterate from 1 to n - 1
    for(int i = 1; i < n; ++i)
    {
        flag = false;
       
        // Iterate from 0 to n - i - 1
        for(int j = 0; j <= (n - i - 1); ++j)
        {
            if (arr[j] > arr[j + 1])
            {
                int temp  = arr[j];
                arr[j] = arr[j + 1];
                arr[j + 1] = temp;
                flag = true;
            }
        }
        if (flag == false)
            break;
    }
}
 
// Driver Code
public static void main(String[] args)
{
    int n = 5;
    int[] arr = { 2, 0, 1, 4, 3 };
    Bubble_Sort(arr, n);
    System.out.print("The Sorted Array by " +
                     "using Bubble Sort is : ");
     
    for(int i = 0; i < n; ++i)
        System.out.print(arr[i] + " ");
}
}
 
// This code is contributed by shubhamsingh10

蟒蛇3

# Python program for the above approach
 
# Function for bubble sort
def Bubble_Sort(arr, n):
    flag = True
     
    # Iterate from 1 to n - 1
    for i in range(1,n):
        flag = False
        # Iterate from 0 to n - i - 1
        for j in range(n-i):
            if (arr[j] > arr[j + 1]):
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
                flag = True
         
        if (flag == False):
            break
         
# Driver Code
n = 5
arr = [2, 0, 1, 4, 3]
Bubble_Sort(arr, n)
print("The Sorted Array by using Bubble Sort is : ", end='')
for i in range(n):
    print(arr[i], end= " ")
 
# This code is contributed by ShubhamSingh10

C#

//C# code for the above approach
using System;
public class GFG{
     
    // Function for bubble sort
    static void Bubble_Sort(int[] arr, int n)
    {
        bool flag;
       
        // Iterate from 1 to n - 1
        for (int i = 1; i < n; ++i) {
     
            flag = false;
           
            // Iterate from 0 to n - i - 1
            for (int j = 0; j <= (n - i - 1); ++j) {
                if (arr[j] > arr[j + 1]) {
                    int temp  = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                    flag = true;
                }
            }
            if (flag == false)
                break;
        }
    }
     
    // Driver Code
    static public void Main ()
    {
        int n = 5;
        int[] arr = { 2, 0, 1, 4, 3 };
        Bubble_Sort(arr, n);
        Console.Write("The Sorted Array by using Bubble Sort is : ");
        for (int i = 0; i < n; ++i)
            Console.Write(arr[i] + " ");
    }
 
}
 
// This code is contributed by shubhamsingh10.
输出
The Sorted Array by using Bubble Sort is : 0 1 2 3 4 

注意:这个小调整不会改变冒泡排序算法的最坏情况时间复杂度,但可以改善特定情况下的运行时间。

参考 :
讲座阅读
实现冒泡排序c

如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程学生竞争性编程现场课程