# Sort an array using Bubble Sort without using loops

• Difficulty Level : Hard
• Last Updated : 22 Jun, 2021

Given an array arr[] consisting of N integers, the task is to sort the given array by using Bubble Sort without using loops.

Examples:

Input: arr[] = {1, 3, 4, 2, 5}
Output: 1 2 3 4 5

Input: arr[] = {1, 3, 4, 2}
Output: 1 2 3 4

Approach: The idea to implement Bubble Sort without using loops is based on the following observations:

• The sorting algorithm of Bubble Sort performs the following steps:
• It can be observed that in every N – 1 iteration, the largest element over the range [0, N – 1 – i] shifts to the position (N – 1 – i) for every i over the range [0, N – 1].
• Therefore, the idea is to use recursion to avoid loops.

Follow the steps below to solve the problem:

• Consider the following base cases:
• If the array contains a single element, simply print the array.
• If the array contains two elements, swap the pair of elements (if required) to obtain a sorted sequence of array elements. Print the sorted array.
• Store the first two elements from the current array in variables, say a and b.
• Initialize an array, say bs[], to store the remaining array elements.
• Place the smaller value among a and b at the front of the current array.
• Recursively repeat the above steps with a new array formed by appending bs[] to the end of the larger value among a and b.
• Store the sorted list returned in a variable, say res[].
• Now, recursively repeat the above steps with a new array formed by appending res[] (excluding the last element) to the end of res[res.size() – 1] ( the last element ).
• After completing the above steps, print the returned list.

Below is the implementation of the above approach:

## C++

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

## Java

 // java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG {   // Function to implement bubble  // sort without using loops  static ArrayList bubble_sort(ArrayList ar)  {     // Base Case: If array    // contains a single element    if (ar.size() <= 1)      return ar;     // Base Case: If array    // contains two elements    if (ar.size() == 2) {      if (ar.get(0) < ar.get(1))        return ar;      else        return new ArrayList(        Arrays.asList(ar.get(1), ar.get(0)));    }     // Store the first two elements    // of the list in variables a and b    int a = ar.get(0);    int b = ar.get(1);     // Store remaining elements    // in the list bs    ArrayList bs = new ArrayList<>();    for (int i = 2; i < ar.size(); i++)      bs.add(ar.get(i));     // Store the list after    // each recursive call    ArrayList res = new ArrayList<>();     // If a < b    if (a < b) {      ArrayList temp1 = new ArrayList<>();      temp1.add(b);      for (int i = 0; i < bs.size(); i++)        temp1.add(bs.get(i));       ArrayList v = bubble_sort(temp1);      v.add(0, a);      res = v;    }     // Otherwise, if b >= a    else {      ArrayList temp1 = new ArrayList<>();      temp1.add(a);      for (int i = 0; i < bs.size(); i++)        temp1.add(bs.get(i));       ArrayList v = bubble_sort(temp1);      v.add(0, b);      res = v;    }     // Recursively call for the list    // less than the last element and    // and return the newly formed list    ArrayList pass = new ArrayList<>();    for (int i = 0; i < res.size() - 1; i++)      pass.add(res.get(i));     ArrayList ans = bubble_sort(pass);    ans.add(res.get(res.size() - 1));    return ans;  }   // Driver Code  public static void main(String[] args)  {     ArrayList arr = new ArrayList(      Arrays.asList(1, 3, 4, 5, 6, 2));    ArrayList res = bubble_sort(arr);     // Print the array    for (int i = 0; i < res.size(); i++)      System.out.print(res.get(i) + " ");  }} // This code is contributed by Kingash.

## Python3

 # Python3 program for the above approach # Function to implement bubble# sort without using loopsdef bubble_sort(ar):       # Base Case: If array    # contains a single element    if len(ar) <= 1:        return ar           # Base Case: If array    # contains two elements    if len(ar) == 2:        return ar if ar[0] < ar[1] else [ar[1], ar[0]]     # Store the first two elements    # of the list in variables a and b    a, b = ar[0], ar[1]     # Store remaining elements    # in the list bs    bs = ar[2:]     # Store the list after    # each recursive call    res = []         # If a < b    if a < b:        res = [a] + bubble_sort([b] + bs)             # Otherwise, if b >= a    else:        res = [b] + bubble_sort([a] + bs)             # Recursively call for the list    # less than the last element and    # and return the newly formed list    return bubble_sort(res[:-1]) + res[-1:]  # Driver Code arr = [1, 3, 4, 5, 6, 2]res = bubble_sort(arr) # Print the arrayprint(*res)

## C#

 // C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to implement bubble// sort without using loopsstatic List bubble_sort(List ar){         // Base Case: If array    // contains a single element    List temp = new List();         if (ar.Count <= 1)        return ar;     // Base Case: If array    // contains two elements    if (ar.Count == 2)    {        if (ar[0] < ar[1])            return ar;        else        {            temp.Add(ar[1]);            temp.Add(ar[0]);            return temp;        }    }     // Store the first two elements    // of the list in variables a and b    int a = ar[0];    int b = ar[1];     // Store remaining elements    // in the list bs    List bs = new List();    for(int i = 2; i < ar.Count; i++)        bs.Add(ar[i]);     // Store the list after    // each recursive call    List res = new List();     // If a < b    if (a < b)    {        List temp1 = new List();        temp1.Add(b);                 for(int i = 0; i < bs.Count; i++)            temp1.Add(bs[i]);                     List v = bubble_sort(temp1);        v.Insert(0, a);        res = v;    }     // Otherwise, if b >= a    else    {        List temp1 = new List();        temp1.Add(a);                 for(int i = 0; i < bs.Count; i++)            temp1.Add(bs[i]);                     List v = bubble_sort(temp1);        v.Insert(0, b);        res = v;    }     // Recursively call for the list    // less than the last element and    // and return the newly formed list    List pass = new List();    for(int i = 0; i < res.Count - 1; i++)        pass.Add(res[i]);     List ans = bubble_sort(pass);    ans.Add(res[res.Count - 1]);    return ans;} // Driver Codepublic static void Main(){    List arr = new List{ 1, 3, 4, 5, 6, 2 };    List res = bubble_sort(arr);     // Print the array    for(int i = 0; i < res.Count; i++)        Console.Write(res[i] + " ");}} // This code is contributed by ukasp

## Javascript



Output:

1 2 3 4 5 6

Time Complexity: O(N2)
Auxiliary Space: O(N)

My Personal Notes arrow_drop_up