Bubble Sort in Java


We will create Java program which will sort Java array, Bubble sort is one of the simplest algorithm.

Basically In bubble sort we travel through all the elements starting from 0th (zeroth) index to n-1(last) index. while traversing through these elements we also perform comparison (compared with adjacent element) and perform swapping (if current element is greater).

Bubble sort algorithm complexity:

Bubble sort features a worst-case and average complexity of О(n2), where n is that the number of things being sorted.

 

package com.onlinetutorials.tech
public class BubbleSortInJava{
public static void main(String[] args){

//Defining int arrays
int[] sampleArray = {36,19,29,12,5};

//Creating temporary variable;
int temp;

for(int i = 0; i < sampleArray.length; i++){
   int tempFlag = 0;

   for(int j = 0; j < sampleArray.length-1-i; j++){
      if(sampleArray[j] > sampleArray[j+1]){
        //Performing swapping of elements using temp
        temp = sampleArray[j];
        sampleArray[j] = sampleArray[j+1];
        sampleArray[j+1] = temp;
        tempFlag = 1;
       }
     }
    if(tempFlag == 0){
       break;
    }
  }
  //Printing all sorted elements
  for(int a: sampleArray){
   System.out.print(a+" ");
  }
 }
}

Here also explaining above loops using following images:

Bubble Sort in Java round1:

Here as we started traversing through array from 0th index and started comparing each other as 36 is the highest element, so we sorted it to last position.

bubble_sort_in_java_example_round1

Bubble Sort in Java round2:

As we already sent the highest element to last position now, will start with next element in array and started comparing with each other as 29 is the highest element, so we sorted it to second last position.

Bubble Sort in Java round3:

As we already sent the second highest element to second last position now, will start with next element in array and started comparing with each other as 19 is the highest element, so we sorted it to respective position.

Bubble Sort in Java round4:

Now again we do the same way iteration, and we will have sorted elements of array.

compareTo() in Java:

compareTo() is used for comparing two string lexicographically each character of both the strings is converted into Unicode value for comparison. if both the strings are equal then this method returns 0(zero) else it returns positive or negative value.

This result is positive if the first string lexicographically greater than the second string else result would be negative.


%d bloggers like this: