Skip to main content

Command Palette

Search for a command to run...

Bubble sort using recursion

Published
•2 min read•View as Markdown
Bubble sort using recursion
N

Hi there, My name is Nirav. I am from India. Currently I am learning Java and Dsa. I can code in Html, Css, Javascript, Python ⭐ My projects:

  1. https://pro-quiz-app.herokuapp.com
  2. https://guessnumberofficial.netlify.app ✨ GitHub: https://github.com/Niravprajapati1/

Hey, Today i sorted an array using Bubble sort with recursion

what is bubble sort ?

bubble sort is an algorithm for sorting an array in ascending order.

In bubble sort we just compare current element with next element of array than if current element is greater than next element swap it.

How to do bubble sort using recursion?

First we break this problem in smaller problems. We compare elements and then swap them.if already at right place just ignore them.

import java.util.Arrays;



public class Sorting{

  public static void main(String[] args) {

int[] arr = {3,2,1};
// we are passing array, array last index and array first index
bubblesort(arr,arr.length,0);

System.out.println(Arrays.toString(arr));

  }
static void bubblesort(int arr[], int end, int start){
//we check if last index is greater than first index
  if(end < start){
    return;
  }
  //This loop will execute if first index is less than last index. this loop will swap biggest element of array with last then for second biggest it will swap with second last element and so on ...
  if(start <= end){
  //this condition is comparing element and swaping them
    if(arr[start] > arr[start+1]){ 
      int tmp = arr[start];  
      arr[start] = arr[start+1];  
      arr[start+1] = tmp; 
}
    //if element is at right place then just check for next element 
   else{

   bubblesort(arr,end,start+1);  

   }

  }
  // this will sort unsorted array and ignore sorted array
  bubblesort(arr,end-1,0); 
}
}