Bubble Sort Implementation - Java

Bubble Sort is a simple algorithm which is used to sort a given set of n elements provided in form of an array with n number of elements. Bubble Sort compares all the element one by one and sorts them based on their values.
If the given array has to be sorted in ascending order, then bubble sort will start by comparing the first element of the array with the second element, if the first element is greater than the second element, it will swap both the elements, and then move on to compare the second and the third element, and so on.
If we have total n elements, then we need to repeat this process for n-1 times.
It is known as bubble sort, because with every complete iteration the largest element in the given array, bubbles up towards the last place or the highest index, just like a water bubble rises up to the water surface.
Sorting takes place by stepping through all the elements one-by-one and comparing it with the adjacent element and swapping them if required.
It works on swapping. It swaps between the numbers if they are in the wrong order.

Code

/**
 *
 * @author A R DANISH
 */
public class BubbleSort {
  
  public void bubbleSort(int arr[]){
    for(int i=0; i < arr.length-1; i++){
      for (int j=0; j<arr.length-i-1; j++){
        if(arr[j]>arr[j+1]){
          int temp = arr[j];
          arr[j] = arr[j+1];
          arr[j+1] = temp;
        }
      }
    }
  }
  //print the array
  public void printArray(int arr[]){
    System.out.println("The array is");
    for(int i=0; i<arr.length; i++){
      System.out.print(arr[i]+ " ");
    }
    System.out.println();
  }
  
  public static void main(String[] args) {
    BubbleSort ob = new BubbleSort();
    int arr[] = {10,45,6,4,84};
    ob.bubbleSort(arr);
    ob.printArray(arr);
  }
  
}

Comments

  1. i am glad to discover this page : i have to thank you for the time i spent on this especially great reading !! i really liked each part and also bookmarked you for new information on your site.
    Top QA Companies
    Top Automation Testing Companies
    Top Mobile App Testing Companies
    Top Performance Testing Companies
    Top Security Testing Companies

    ReplyDelete
  2. Wonderful blog about Software Testing Services in Chennai to read and further more tips on the Software Testing Services in India have been learnt. It's great time spending on this. I am waiting for new post here about Software Testing Companies in Bangalore and Please keep it up in future..

    Consult today to - Software Testing Services in Mumbai

    ReplyDelete

Post a Comment

Popular posts from this blog

Day 4: Class vs. Instance - HackerRank 30 days of code solution

Day 27: Testing - HackerRank 30 days of code solution

Day 11: 2D Arrays - HackerRank 30 days of code solution