ในส่วนนี้เราจะดูวิธีการอีกแบบของเทคนิค Bubble Sort ที่มีชื่อเสียง เราเคยใช้ Bubble แบบ iterative (วนซ้ำ) แต่ที่นี่เราจะดู recursive approach (วิธีการเรียกซ้ำ) ของ Bubble Sort อัลกอริทึม Recursive Bubble Sort 长得像这样
อัลกอริทึม
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 current element is greater than next one
swap(arr[i], arr[i+1]); // swap elements
recBubble(arr, n - 1);
}
int 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