Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม 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