在本节中,我们将看到著名的气泡分类技术的另一种方法。我们以迭代方式使用了冒泡排序。但是在这里,我们将看到气泡排序的递归方法。递归气泡排序算法如下所示。
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