C++ 递归冒泡排序程序?


在本节中,我们将看到另一个著名的冒泡排序技术的方法。我们以迭代的方式使用冒泡排序。但在这里,我们将看到冒泡排序的递归方法。递归冒泡排序算法如下所示。

算法

bubbleRec(arr, n)

begin
   if n = 1, return
   for i in range 1 to n-2, do
      if arr[i] > arr[i+1], then
         exchange arr[i] and arr[i+1]
      end if
   done
   bubbleRec(arr, n-1)
end

实例

 实时演示

#include<iostream>
using namespace std;
void recBubble(int arr[], int n){
   if (n == 1)
      return;
   for (int i=0; i<n-1; i++) //for each pass p
      if (arr[i] > arr[i+1]) //if the current element is greater than next one
   swap(arr[i], arr[i+1]); //swap elements
   recBubble(arr, n-1);
}
main() {
   int data[] = {54, 74, 98, 154, 98, 32, 20, 13, 35, 40};
   int n = sizeof(data)/sizeof(data[0]);
   cout << "Sorted Sequence ";
   recBubble(data, n);
   for(int i = 0; i <n;i++){
      cout << data[i] << " ";
   }
}

输出

Sorted Sequence 13 20 32 35 40 54 74 98 98 154

更新于:30-7-2019

905 次浏览

开启您的 职业

通过完成课程取得认证

开始
广告
© . All rights reserved.