Sort an array using Bubble Sort without using loops | C ++ program for the above approach ; Function to implement bubble sort without using loops ; Base Case : If array contains a single element ; Base Case : If array contains two elements ; Store the first two elements of the list in variables a and b ; Store remaining elements in the list bs ; Store the list after each recursive call ; If a < b ; Otherwise , if b >= a ; Recursively call for the list less than the last element and and return the newly formed list ; Driver Code ; Print the array
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < int > bubble_sort ( vector < int > ar ) { if ( ar . size ( ) <= 1 ) return ar ; if ( ar . size ( ) == 2 ) { if ( ar [ 0 ] < ar [ 1 ] ) return ar ; else return { ar [ 1 ] , ar [ 0 ] } ; } int a = ar [ 0 ] ; int b = ar [ 1 ] ; vector < int > bs ; for ( int i = 2 ; i < ar . size ( ) ; i ++ ) bs . push_back ( ar [ i ] ) ; vector < int > res ; if ( a < b ) { vector < int > temp1 ; temp1 . push_back ( b ) ; for ( int i = 0 ; i < bs . size ( ) ; i ++ ) temp1 . push_back ( bs [ i ] ) ; vector < int > v = bubble_sort ( temp1 ) ; v . insert ( v . begin ( ) , a ) ; res = v ; } else { vector < int > temp1 ; temp1 . push_back ( a ) ; for ( int i = 0 ; i < bs . size ( ) ; i ++ ) temp1 . push_back ( bs [ i ] ) ; vector < int > v = bubble_sort ( temp1 ) ; v . insert ( v . begin ( ) , b ) ; res = v ; } vector < int > pass ; for ( int i = 0 ; i < res . size ( ) - 1 ; i ++ ) pass . push_back ( res [ i ] ) ; vector < int > ans = bubble_sort ( pass ) ; ans . push_back ( res [ res . size ( ) - 1 ] ) ; return ans ; } int main ( ) { vector < int > arr { 1 , 3 , 4 , 5 , 6 , 2 } ; vector < int > res = bubble_sort ( arr ) ; for ( int i = 0 ; i < res . size ( ) ; i ++ ) cout << res [ i ] << " ▁ " ; }