ใน Bubble Sort จะเปรียบเทียบคู่ที่อยู่ติดกันและสลับกันถ้าอยู่ในลำดับผิด ในประเภท Bubble Sort นี้ เราใช้ฟังก์ชัน recursive ที่เรียกตัวเอง
Input: 5 3 4 2 1 Output: 1 2 3 4 5
คำอธิบาย
ใช้ recursive function (ฟังก์ชันเรียกตัวเอง) เปรียบเทียบคู่ที่อยู่ติดกันและสลับถ้าลำดับผิด จนกว่าอาร์เรย์จะเรียงลำดับครบ
ตัวอย่างโค้ด
#include <iostream>
using namespace std;
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
if (arr[i] > arr[i + 1]) {
int temp = arr[i];
arr[i] = arr[i + 1];
arr[i + 1] = temp;
}
}
if (n - 1 > 1) {
bubbleSort(arr, n - 1);
}
}
int main() {
int arr[] = {5, 4, 2, 1, 3};
int n = 5;
bubbleSort(arr, n);
for (int i = 0; i < n; i++) {
cout << arr[i] << "\t";
}
return 0;
}