📜  递归气泡排序

📅  最后修改于: 2021-05-04 12:02:29             🧑  作者: Mango

背景 :
冒泡排序是最简单的排序算法,它可以通过以错误顺序重复交换相邻元素来工作。
例子:
第一遍:
( 5 1 4 2 8)–>( 1 5 4 2 8),此处,算法比较前两个元素,并从5> 1开始交换。
(1 5 4 2 8)–>(1 4 5 2 8),从5> 4开始交换
(1 4 5 2 8)–>(1 4 2 5 8),从5> 2开始交换
(1 4 2 5 8 )–>(1 4 2 5 8 ),现在,由于这些元素已经按顺序排列(8> 5),因此算法不会交换它们。
第二遍:
( 1 4 2 5 8)–>( 1 4 2 5 8)
(1 4 2 5 8)–>(1 2 4 5 8),交换自4> 2
(1 2 4 5 8)–>(1 2 4 5 8)
(1 2 4 5 8 )–>(1 2 4 5 8 )
现在,该数组已经排序,但是我们的算法不知道它是否完成。该算法需要一遍而无需任何交换就可以知道它已被排序。
第三关:
( 1 2 4 5 8)–>( 1 2 4 5 8)
(1 2 4 5 8)–>(1 2 4 5 8)
(1 2 4 5 8)–>(1 2 4 5 8)
(1 2 4 5 8 )–>(1 2 4 5 8 )
以下是迭代冒泡排序算法:

// Iterative Bubble Sort
bubbleSort(arr[], n)
{
  for (i = 0; i < n-1; i++)      

     // Last i elements are already in place   
     for (j = 0; j < n-i-1; j++)
     {
         if(arr[j] > arr[j+1])
             swap(arr[j], arr[j+1]);
     }
} 

有关更多详细信息,请参见气泡排序。
如何递归实现?
递归冒泡排序没有性能/实现方面的优势,但是对于检查人们对冒泡排序和递归的理解可能是一个很好的问题。
如果我们仔细研究冒泡排序算法,我们会注意到在第一遍中,我们将最大的元素移到末尾(假设排序按升序排列)。在第二遍中,我们将第二大元素移至倒数第二个位置,依此类推。
递归的想法。

  1. 基本情况:如果数组大小为1,则返回。
  2. 进行一次普通气泡排序一遍。此遍可修复当前子数组的最后一个元素。
  3. 对于除当前子数组的最后一个元素以外的所有元素重复执行。

以下是上述想法的实现。

C++
// C/C++ program for recursive implementation
// of Bubble sort
#include 
using namespace std;
 
// A function to implement bubble sort
void bubbleSort(int arr[], int n)
{
    // Base case
    if (n == 1)
        return;
 
    // One pass of bubble sort. After
    // this pass, the largest element
    // is moved (or bubbled) to end.
    for (int i=0; i arr[i+1])
            swap(arr[i], arr[i+1]);
 
    // Largest element is fixed,
    // recur for remaining array
    bubbleSort(arr, n-1);
}
 
/* Function to print an array */
void printArray(int arr[], int n)
{
    for (int i=0; i < n; i++)
        printf("%d ", arr[i]);
    printf("\n");
}
 
// Driver program to test above functions
int main()
{
    int arr[] = {64, 34, 25, 12, 22, 11, 90};
    int n = sizeof(arr)/sizeof(arr[0]);
    bubbleSort(arr, n);
    printf("Sorted array : \n");
    printArray(arr, n);
    return 0;
}


Java
// Java program for recursive implementation
// of Bubble sort
 
import java.util.Arrays;
 
public class GFG
{
    // A function to implement bubble sort
    static void bubbleSort(int arr[], int n)
    {
        // Base case
        if (n == 1)
            return;
      
        // One pass of bubble sort. After
        // this pass, the largest element
        // is moved (or bubbled) to end.
        for (int i=0; i arr[i+1])
            {
                // swap arr[i], arr[i+1]
                int temp = arr[i];
                arr[i] = arr[i+1];
                arr[i+1] = temp;
            }
      
        // Largest element is fixed,
        // recur for remaining array
        bubbleSort(arr, n-1);
    }
     
    // Driver Method
    public static void main(String[] args)
    {
        int arr[] = {64, 34, 25, 12, 22, 11, 90};
      
        bubbleSort(arr, arr.length);
         
        System.out.println("Sorted array : ");
        System.out.println(Arrays.toString(arr));
    }
}


Python3
# Python Program for implementation of
# Recursive Bubble sort
class bubbleSort:
    """
     bubbleSort:
          function:
              bubbleSortRecursive : recursive
                  function to sort array
              __str__ : format print of array
              __init__ : constructor
                  function in python
          variables:
              self.array = contains array
              self.length = length of array
    """
 
    def __init__(self, array):
        self.array = array
        self.length = len(array)
 
    def __str__(self):
        return " ".join([str(x)
                        for x in self.array])
 
    def bubbleSortRecursive(self, n=None):
        if n is None:
            n = self.length
 
        # Base case
        if n == 1:
            return
 
        # One pass of bubble sort. After
        # this pass, the largest element
        # is moved (or bubbled) to end.
        for i in range(n - 1):
            if self.array[i] > self.array[i + 1]:
                self.array[i], self.array[i +
                1] = self.array[i + 1], self.array[i]
 
        # Largest element is fixed,
        #  recur for remaining array
        self.bubbleSortRecursive(n - 1)
 
# Driver Code
def main():
    array = [64, 34, 25, 12, 22, 11, 90]
     
    # Creating object for class
    sort = bubbleSort(array)
     
    # Sorting array
    sort.bubbleSortRecursive()
    print("Sorted array :\n", sort)
 
 
if __name__ == "__main__":
    main()
 
# Code contributed by Mohit Gupta_OMG,
# improved by itsvinayak


C#
// C# program for recursive
// implementation of Bubble sort
using System;
 
class GFG
{
 
// A function to implement
// bubble sort
static void bubbleSort(int []arr,  
                       int n)
{
    // Base case
    if (n == 1)
        return;
 
    // One pass of bubble
    // sort. After this pass,
    // the largest element
    // is moved (or bubbled)
    // to end.
    for (int i = 0; i < n - 1; i++)
        if (arr[i] > arr[i + 1])
        {
            // swap arr[i], arr[i+1]
            int temp = arr[i];
            arr[i] = arr[i + 1];
            arr[i + 1] = temp;
        }
 
    // Largest element is fixed,
    // recur for remaining array
    bubbleSort(arr, n - 1);
}
 
// Driver code
static void Main()
{
    int []arr = {64, 34, 25,
                 12, 22, 11, 90};
 
    bubbleSort(arr, arr.Length);
     
    Console.WriteLine("Sorted array : ");
    for(int i = 0; i < arr.Length; i++)
    Console.Write(arr[i] + " ");
}
}
 
// This code is contributed
// by Sam007


输出 :

Sorted array :
11 12 22 25 34 64 90