Breaking

Post Top Ad

Your Ad Spot

Thursday, 4 March 2021

Bubble Sort Algorithm with Easy code

Bubble Sort Algorithm Easy Implementation in Java

Hey, all today I am back with another important post related to the bubble sort algorithm which I will show to implement in java. So let's get started.




bubble algorithm simple
bubble algorithm simple



I am following a udemy course where I learned it with easy implementation. We have an array of few integers that we will sort. First, we create a swap method that will be used to swap to different  elements
This swap method is fully optimized to make this bubble sort algorithm a stable algorithm because here the position of the same value of integer elements will be preserved. 
Them using nested for loop we will implement the rest of code that will use this swapping method.

Basic and easy implementation for Bubble Sort is:


public class BubbleSort{
    public static void main(String []args){
        int arr[]= {-20121514, -215 };
        for(int i=arr.length-1;i>=0;i--)//run form 5 to 0
           {
            for(int j=0;j<i;j++){ inner loop from 0 to value of i
                if(arr[j]>arr[j+1])
                swap(arr,j,j+1);
            }
        }
        for(int i=0;i<arr.length;i++){
            System.out.println(arr[i]);
        }
    }
    public static void swap(int []arr, int i, int j ){
        if(i==j){
            return ;
        }
       
            int temp= arr[i];
            arr[i]=arr[j];
            arr[j]=temp;
        
    }
}

I hope you understood this algorithm for any doubts and queries you can comment down below


No comments:

Post a Comment

Post Top Ad

Your Ad Spot

Pages