C++ Program for the Recursive Bubble Sort?


In Bubble sort compares adjacent pairs and swaps them if they are in the wrong order. In this type of bubble sort we use the recursive function that calls itself.

Input:53421
Output:12345

Explanation

Use of recursive (self-calling) function compares adjacent pairs and swaps them if they are in the wrong order until the array is in order

Example

#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;
}

Updated on: 19-Aug-2019

352 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements